Lop*_*c92 1 c# sql sql-server ado.net
我是C#编码的新手,并且环顾四周,但很难推断出我的问题的答案.
我目前只是试图将组合框中的文本和选定文本添加到简单的数据库表中.但是,当我尝试添加信息时,我得到一个SqlException错误未处理.我已经查看了其他答案,看到它可能与添加连接有关,我尝试过但它仍然无法正常工作......
我的代码和错误消息,如下面的图像链接,但以防万一这里也是我的代码,
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace SavetoDbTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection test = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\Visual Studio 2015\\Projects\\SavetoDbTest\\SavetoDbTest\\Hobbie.mdf;Integrated Security=True"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("@Name", textBox1.Text);
again.Parameters.AddWithValue("@Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
+1尝试使用参数化查询!但你做得不对:-)
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("@Name", textBox1.Text);
again.Parameters.AddWithValue("@Hobby", comboBox1.Text);
Run Code Online (Sandbox Code Playgroud)
当查询字符串不期望它们时,这会添加参数.可能这也是你所看到的例外的原因.
您的查询字符串必须如下所示:
again.CommandText = "INSERT INTO [Table] Values(@Name, @Hobby)";
Run Code Online (Sandbox Code Playgroud)
另外,TABLE是SQL中的保留字.因此,如果您的表已命名Table,则应将其包装在方括号中.