【问题标题】:How to connect this project with sql如何用sql连接这个项目
【发布时间】:2019-04-06 18:58:26
【问题描述】:

executenonquery() 错误 c# 这就是我的代码的样子

con.Open();

String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();

String id = textBox3.Text.ToString();
int iid = Int32.Parse(id);

String semester = textBox4.Text.ToString();
int i_sem = Int32.Parse(semester);

String field = comboBox1.SelectedItem.ToString();

String qry = "insert into Table values('" + name + "','" + address + "'," + iid + "," + i_sem + ",'" + field + "',)";

SqlCommand cmd = new SqlCommand(qry, con);

cmd.ExecuteNonQuery();

executenonquery() 总是让我烦恼!

int i = cmd.ExecuteNonQuery();

【问题讨论】:

  • 我已经看到了多个问题,但请分享您希望我们解决的问题。我们不知道您收到了什么错误消息...
  • 您的 SQL 错误。最后有,
  • 当我按下插入按钮将文件存储在 sql 表中时,它说.... System.Data.SqlClient.SqlException(0x80131904):表值附近的语法不正确!
  • 请用这些错误信息更新问题
  • 你的表名是什么?似乎您需要在插入脚本中使用您的表名更新 TABLE。

标签: c# sql-server asp.net-mvc sqlconnection


【解决方案1】:

你需要解决几个问题:

  1. 删除查询中的最后一个,。
  2. 我不知道您的数据库中是否有一个名为 Table 的表,但您应该检查名称是否正确。
  3. 当您不知道如何更正代码时,最好使用 try-catch 语句来了解代码中真正的问题所在。 Here is an example 关于如何处理 C# 代码中的 SQL 异常。
  4. 您收到 SqlException 是因为您的查询语法错误,但是还有另一种方法可以将 SQL 参数添加到您的查询中,而无需使用字符串变量。您可以使用SqlParameterCollection.AddWithValue(String, Object) 方法来获得相同的结果并避免SQL 注入:
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into YourTableName (name, address, id, semester, field) VALUES (@name, @address, @id, @semester, @field)";
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@address", address);
command.Parameters.AddWithValue("@id", iid);
command.Parameters.AddWithValue("@semester", i_sem);
command.Parameters.AddWithValue("@field", field);

try
{
    connection.Open();
    int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
    // error here
}
finally
{
    connection.Close(); //close your connection if you do not need to keep it open
}

更多信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 2019-09-19
    • 1970-01-01
    • 2023-02-19
    • 2021-06-25
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    相关资源
    最近更新 更多