2012-05-01 4 views
2

다음 코드를 사용하여 TextBox 값을 데이터베이스에 저장합니다. 그러나 값을 삽입하면 새 행에 저장됩니다. 같은 행에 어떻게 저장할 수 있습니까?데이터베이스에 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(); 
} 
+0

기록을 어떻게 식별합니까? –

답변

4

삽입 대신 업데이트 명령을 사용하십시오. 당신은 당신의 레코드에 대한 UPDATE 문을 작성해야

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

:

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

코드를 작성할 수 있습니까? – aliprogrammer

+0

Acutally, 아니야. 그것은 어떤 이유로 든 내 게시물을 편집 할 수 없으므로 여기에 넣어 보겠습니다. –

+0

cmd.CommandText = "YourTable을 업데이트하십시오. FieldName = YourValue 여기서 KeyField = YourKeyValue"; –

2

는 대신 이와 유사한 INSERT의 업데이트를 사용해야합니다. 당신의 의도를 업데이트하는 경우 모든 다음 문은 다음과 같습니다

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 [email protected]" 
    cmd.Parameters.AddWithValue("@pass", pass); 
    cmd.Parameters.AddWithValue("@id", 1); 
    sql.Open(); 
    cmd.ExecuteNonQuery(); 
    sql.Close(); 
} 

가 ADO를 사용하여 설명하는 몇 가지 샘플 웹 사이트입니다 UPDATE 할 레코드를 말하고 싶은 것입니다. NET :

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

How to use UPDATE in ado net

+0

이 효과가 있습니다. thanks – aliprogrammer

+1

업데이트 할 올바른 행을 지정해야한다는 것을 알려주는 경우, 그렇지 않으면 사용자의 의도와 다른 것으로 생각되는 모든 행이 업데이트됩니다. – Taryn

+0

예 모든 행을 업데이트합니다. 내 의도 행에 대해 어떻게 업데이트 할 수 있습니까? – aliprogrammer

관련 문제