【问题标题】:Insert TextBox Value in Database在数据库中插入文本框值
【发布时间】:2012-11-25 16:42:45
【问题描述】:

我使用以下代码将 TextBox 值保存到数据库中。但是,当我插入该值时,它将保存在新行中。如何将其保存到同一行?

private void button1_Click(object sender, EventArgs e)
{
    string pass = textBox1.Text;
    sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=P3;Integrated Security=True");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = sql;
    cmd.CommandText = ("Insert [MyTable] ([MyColumn]) Values (@pass)");
    cmd.Parameters.AddWithValue("@pass", pass);
    sql.Open();
    cmd.ExecuteNonQuery();
    sql.Close();
}

【问题讨论】:

  • 如何识别记录?

标签: c# sql ado.net


【解决方案1】:

使用更新命令代替插入。

cmd.CommandText = "update YourTable set FieldName = YourValue where KeyField = YourKeyValue"

【讨论】:

  • 实际上,不,我不能。由于某种原因,它不允许我编辑我的帖子......所以我会尝试把它放在这里。
  • cmd.CommandText = "update YourTable set FieldName = YourValue where KeyField = YourKeyValue";
【解决方案2】:

您需要使用 UPDATE 而不是 INSERT,类似于:

UPDATE yourTable
SET yourColumn = newValue
WHERE (your criteria needs to go here) ID = recordId

您需要为记录创建 UPDATE 语句。如果您打算全部更新,那么您的声明将是:

UPDATE yourTable
SET yourColumn = newValue

否则,您将需要告诉它要更新哪些记录

UPDATE yourTable
SET yourColumn = newValue
WHERE ID = yourID

private void button1_Click(object sender, EventArgs e)
{
    string pass = textBox1.Text;
    sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=P3;Integrated Security=True");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = sql;
    cmd.CommandText = "UPDATE MyTable SET MyColumn = @pass WHERE id=@id"
    cmd.Parameters.AddWithValue("@pass", pass);
    cmd.Parameters.AddWithValue("@id", 1);
    sql.Open();
    cmd.ExecuteNonQuery();
    sql.Close();
}

这是一个网站,其中包含一些使用 ADO.NET 进行说明的示例:

Simple ADO.NET Database Read, Insert, Update and Delete using C#

How to use UPDATE in ado net

【讨论】:

  • WHERE 告诉您,您需要指定要更新的正确行,否则您将更新所有我认为不是您的意图的行。
  • 是的,它将更新所有行。我怎样才能为我的意图行更新它?
  • 我已经更新了我的答案,您需要传入第二个参数,告诉它要更新哪一行。我用一个例子引用了另一个关于 SO 的问题
  • 您没有阅读每个人都在告诉您的内容吗?这是基本的 SQL。在继续之前你需要学习基本的 SQL!
猜你喜欢
  • 2011-05-05
  • 1970-01-01
  • 1970-01-01
  • 2015-03-10
  • 2020-12-22
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 2018-11-15
相关资源
最近更新 更多