我试图将我表单中文本框中的用户详细信息提供给访问中的数据库,这应该保存。但是,每次我点击注册时,我都会收到错误信息,以下代码是我试图写出来的:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
但是我认为问题实际上来自这一部分:
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
答案 0 :(得分:0)
真的是你的查询不可读。任何类型的错误都可能隐藏在字符串连接的丛林中,并且随处可见单引号。 (可能是从复制/粘贴操作的修复中删除了不必要的逗号)
您应该使用参数化查询,所有这些都将消失
command.Connection = connection;
string sql = "UPDATE enroll SET SSN=?, Name=?, Company=? WHERE ID=?";
command.CommandText = sql;
command.Parameters.AddWithValue("@p1", txtSSN.Text);
command.Parameters.AddWithValue("@p2", txtName.Text );
command.Parameters.AddWithValue("@p3", txtCompany.Text);
command.Parameters.AddWithValue("@p4", _UserID);
command.ExecuteNonQuery();
现在我认为这实际上更具可读性,没有引号要添加,因为框架知道每个参数的数据类型,并将使用所需的适当引用。最后但同样重要的是,Sql Injection
没问题