NpgsqlConnection conn = new NpgsqlConnection(SqlHelper.sqlcon); NpgsqlCommand sqlCmd = new NpgsqlCommand(); //创建执行sql的对象 try { conn.Open(); string sql = "update login set login_no='" + yhbh.Text.Trim() + "',login_name='" + yhmc.Text.Trim() + "',login_pwd='" + yhmm.Text.Trim() + "',login_dept='" + bm.Text.Trim() + "',login_job='" + zw.Text.Trim() + "',login_nation='" + textBox11.Text.Trim() + "',login_birthday='" + dateTimePicker1.Text.Trim() + "',login_phone='" + dh.Text.Trim() + "',login_mail='" + yx.Text.Trim() + "' where login_no='" + dataInfo.No + "'"; sqlCmd = new NpgsqlCommand(sql, conn); sqlCmd.ExecuteNonQuery(); MessageBox.Show("修改成功!", "提示"); } catch (Exception ex2) { MessageBox.Show("连接数据库发生错误:" + ex2.ToString(), "错误!"); } finally { sqlCmd.Dispose(); conn.Close(); button2_Click_1(this, e); }转化
时间: 2024-01-12 18:02:59 浏览: 158
以下是可能的另一种实现方式:
```
using (NpgsqlConnection conn = new NpgsqlConnection(SqlHelper.sqlcon))
using (NpgsqlCommand sqlCmd = new NpgsqlCommand("UPDATE login SET login_no = @login_no, login_name = @login_name, login_pwd = @login_pwd, login_dept = @login_dept, login_job = @login_job, login_nation = @login_nation, login_birthday = @login_birthday, login_phone = @login_phone, login_mail = @login_mail WHERE login_no = @old_login_no", conn))
{
sqlCmd.Parameters.AddWithValue("@login_no", yhbh.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_name", yhmc.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_pwd", yhmm.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_dept", bm.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_job", zw.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_nation", textBox11.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_birthday", dateTimePicker1.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_phone", dh.Text.Trim());
sqlCmd.Parameters.AddWithValue("@login_mail", yx.Text.Trim());
sqlCmd.Parameters.AddWithValue("@old_login_no", dataInfo.No);
try
{
conn.Open();
int rowsAffected = sqlCmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("修改成功!", "提示");
button2_Click_1(this, e);
}
else
{
MessageBox.Show("未找到对应的用户记录!", "提示");
}
}
catch (Exception ex)
{
MessageBox.Show("连接数据库发生错误:" + ex.ToString(), "错误!");
}
}
```
该代码片段使用了 `using` 语句块来确保 `NpgsqlConnection` 和 `NpgsqlCommand` 对象被正确释放。另外,该代码片段使用了参数化查询来避免 SQL 注入攻击,并且在执行更新操作后检查受影响的行数,根据情况显示不同的提示信息。
阅读全文