C# SQL connection
本文关键字:connection SQL | 更新日期: 2023-09-27 18:04:15
我想用GUI创建简单的应用程序,在那里我可以输入SQL Server名称和id,必须用这个字符串更新:
update docs SET locked=0 WHERE ID=(id entered in GUI)
任何建议吗?
你可以写一个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");
}
。. 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();
}
- txtid改变"。
- 您也可以检查res以找出受影响的行数。
将连接字符串更改为您自己的连接字符串
更改(本地)到localhost'SQLEXPRESS如果你正在使用SQL Express。