我想用GUI创建简单的应用程序,我可以输入必须使用此字符串更新的 SQL Server 名称和ID:
update docs SET locked=0 WHERE ID=(id entered in GUI)
有什么建议吗?
答案 0 :(得分: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");
}
答案 1 :(得分: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();
}