【问题标题】:C# simple code to write an INSERT query is giving an exception编写 INSERT 查询的 C# 简单代码给出异常
【发布时间】:2014-11-18 20:23:50
【问题描述】:

我有一个非常基本的初学者问题。我有一个 5 行代码,但其中有异常。

我的数据库:

它有一个表和表内的两列即。身份证和姓名。 我做了一个表格。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
    conn.Open();
    SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
    command.ExecuteNonQuery();
    conn.Close();

}

运行代码时出现以下异常:

它说我有语法错误,即使语法错误是正确的。任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 表和名称可能是关键字。我会避免使用它们。另外,使用参数避免sql注入。
  • 尝试在 [...] 之间嵌入您的姓名
  • 有一个很可爱的xkcd解释了你的这行代码:'" + textBox1.Text + "'
  • 如果你真的想在 SQL Server 中使用 'Table' 作为你的表名,请将其括在方括号中 -- 即:SqlCommand command = new SqlCommand("INSERT INTO [Table] (id,name) VALUES (1,'" + textBox1 + "')", conn);
  • 请采纳 LarsTech 的建议,不要使用关键字作为标识符。 Table 无论如何都是一个可怕的名字。还要研究SQL injection,因为您的命令有严重错误。

标签: c# sql .net sql-server visual-studio


【解决方案1】:

您应该使用 using 子句来正确管理资源并使用参数来避免安全问题。不建议使用保留字作为“表”。试试这个:

const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,@Name)";

using (SqlConnection connection = new SqlConnection(ConnectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.Add("@Name", SqlDbType.VarChar);
    command.Parameters["@Name"].Value = textBox1.Text;

    connection.Open();
    var rowsAffected = command.ExecuteNonQuery();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多