在数据库中插入TextBox值

时间:2012-05-01 20:21:18

标签: c# sql ado.net

我使用以下代码将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();
}

2 个答案:

答案 0 :(得分:4)

使用更新命令而不是插入。

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

答案 1 :(得分:2)

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

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

您需要为记录创建UPDATE语句。如果您打算更新所有内容,那么您的陈述将是:

UPDATE yourTable
SET yourColumn = newValue

否则,您需要告诉它哪些记录为UPDATE

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