c# - SqlException 在 C# 中未处理 - 数据库表中的信息

标签 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");

                }
            }      
        }
    }
}

enter image description here

最佳答案

+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/

相关文章:

c# - 如何在执行相同功能时避免 C# 中的短路评估

mysql - SQL无法创建表,errno 150

sql - 参数化 SQL 查询中变量的影响

sql-server - 将 for xml 原始查询的结果写入文件 vb.net

sql-server - 我的全文搜索查询出了什么问题?

c# - 在 SqlBulkCopy 期间更改值

c# - 如何将表单的背景图像设置为用户选择的图像?

c# - xsl 格式日期(子字符串 + 连接?)

mysql - 左外连接与子查询以包含没有员工的部门

sql - 在 SQL 中使用 [a-9] 而不是 [0-Z] 的 ORDER BY varchar