2013-03-17 45 views
0

我想与图形用户界面,创建简单的应用程序,我可以输入SQL服务器姓名和身份证必须与此字符串进行更新:C#SQL连接

update docs SET locked=0 WHERE ID=(id entered in GUI) 

什么建议吗?

+2

添加代码已经试过! – KF2 2013-03-17 16:41:42

回答

7

你可以写一个C#函数,将执行更新:

public int Update(int id) 
{ 
    string connectionString = "... put the connection string to your db here ..."; 
    using (var conn = new SqlConnection(connectionString)) 
    using (var cmd = conn.CreateCommand()) 
    { 
     conn.Open(); 
     cmd.CommandText = "UPDATE docs SET locked = 0 WHERE ID = @id"; 
     cmd.Parameters.AddWithValue("@id", id); 
     return cmd.ExecuteNonQuery(); 
    } 
} 

,然后你可以通过它传递您从UI获得的一些动态值调用这个函数:

int id; 
if (int.TryParse(someTextBox.Text, out id)) 
{ 
    int affectedRows = Update(id); 
    if (affectedRows == 0) 
    { 
     MessageBox.Show("No rows were updated because the database doesn't contain a matching record"); 
    } 
} 
else 
{ 
    MessageBox.Show("You have entered an invalid ID"); 
} 
0

.Net框架使用ADO.Net进行SQL连接。在ADO.Net一个简单的查询可以这样执行:

SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Yourdatabase;Integrated Security=SSPI"); 
int res = 0; 
try 
{ 
conn.Open(); 
SqlCommand cmd = new SqlCommand("update docs SET locked=0 WHERE ID= @id"); 
cmd.Parameters.AddWithValue("@id", txtid.text); 
res = cmd.ExecuteNonQuery(); 
}catch(Exception err){ 
MessageBox.Show(err.getMessage()); 
}finally{ 
conn.Close(); 
} 
  1. 更改连接字符串以自己的连接字符串。
  2. 如果您使用的是SQL Express,请将local local更改为localhost \ SQLEXPRESS。
  3. 将“txtid.text”更改为将为您获取您的ID的任何语句。
  4. 您也可以检查res以找出受影响的行数。