【问题标题】:C# SQL INSERT wont be savedC# SQL INSERT 不会被保存
【发布时间】:2018-02-04 21:21:02
【问题描述】:

我试图在 mssql 数据库中插入一个新行,但它不会被保存。谁能告诉我问题是什么?

string connectionString = Properties.Settings.Default.DonationsConnectionString;

System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection(connectionString);

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT Donations (Name, Betrag) VALUES ('" + donator.Text + "', '" + betrag.Text + "')";
cmd.Connection = sqlConnection1;

sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();

【问题讨论】:

  • 插入我猜
  • 不要这样创建 SQL;研究保留字,一个像样的SQL Tutorial 不会伤害并阅读How to Ask 并采取tour。如果您需要帮助,您必须提供更多信息,例如错误消息。
  • 请不要发布包括 SQL 注入在内的示例。这会导致讨论与您的实际问题完全脱轨,并可能导致投票失败,因为这可能表明缺乏研究(没有人研究如何进行 SQL 查询以忽略参数化查询)
  • 如果没有错误那么可能是stackoverflow.com/questions/17147249/…(并且不要忽视有关sql注入的建议)
  • 请描述“它不会被保存”。你是说你执行了语句,什么都没有插入,没有异常发生?

标签: c# sql sql-server database insert


【解决方案1】:

我想你忘记了插入 sql 语法的“INTO”

cmd.CommandText = "INSERT INTO Donations (Name, Betrag) VALUES ('" + donator.Text + "', '" + betrag.Text + "')";

但我建议你这样改变

cmd.CommandText = "INSERT INTO Donations (Name, Betrag) VALUES(@donator_temp,@betrag_temp);

cmd.Parameters.Add("@donator_temp", donator.text);
cmd.Parameters.Add("@betrag_temp", betrag.text);

cmd.ExecuteNonQuery();

【讨论】:

    猜你喜欢
    • 2018-05-04
    • 1970-01-01
    • 2023-01-28
    • 2011-12-05
    • 1970-01-01
    • 2015-04-11
    • 2017-11-08
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多