我是 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");
}
}
}
}
}
最佳答案
+1 尝试使用参数化查询!但是你做的不对:-)
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("@Name", textBox1.Text);
again.Parameters.AddWithValue("@Hobby", comboBox1.Text);
这会在查询字符串不需要参数时添加参数。可能这也是您所看到的异常的原因。
您的查询字符串必须如下所示:
again.CommandText = "INSERT INTO [Table] Values(@Name, @Hobby)";
此外,TABLE
是 SQL 中的保留字。因此,如果您的表名为 Table
,则应将其括在方括号中。
关于c# - SqlException 在 C# 中未处理 - 数据库表中的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39366549/