【发布时间】:2013-11-15 23:31:09
【问题描述】:
我正在尝试运行以下代码:
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtNewPassword.Text.Length > 4 && txtNewPassword.Text.Equals(txtConfirmPassword.Text))
{
try
{
OleDbConnection connection = new OleDbConnection(MDFConfiguration.getConnectionString());
connection.Open();
int updatedRecordCount = updateExistingUserRecord(connection);
if (updatedRecordCount > 0)
{
MessageBox.Show("Password Changed Successfully");
}
else
{
MessageBox.Show("There was some error during updated");
}
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show("exception: " + ex.ToString());
}
}
else
{
MessageBox.Show("New Password does not match required criteria");
}
}
private int updateExistingUserRecord(OleDbConnection connection)
{
string sql = "UPDATE " + MDFConfiguration.LOGIN_INFO_TABLE + " SET " +
" password = '" + MDFUtils.CreateMD5Hash(txtNewPassword.Text) + "' WHERE " +
" login_name = '" + cmbLoginNames.SelectedItem.ToString() + "'";
Console.WriteLine("sql = " + sql);
OleDbCommand command = new OleDbCommand(sql, connection);
return command.ExecuteNonQuery();
}
当我运行此代码时,它会在运行时的查询中出现语法错误,但是当我直接在 MS Acess 中运行上面这段代码中由 Console.WriteLine 打印的相同查询时,它运行时没有任何错误。
Console.WriteLine 打印以下查询:
UPDATE MDF_LOGIN_INFO SET password = 'E206A54E97690CCE50CC872DD70EE896' WHERE login_name = 'admin'
异常日志:
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
System.Data.OleDb.OleDbException (0x80040E14): Syntax error in UPDATE statement.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at MDFData.AdminToolForm.updateExistingUserRecord(OleDbConnection connection) in c:\Users\UBAID ULLAH\Documents\Visual Studio 2012\Projects\Backup MDFData\MDFData\AdminToolForm.cs:line 114
at MDFData.AdminToolForm.btnUpdate_Click(Object sender, EventArgs e) in c:\Users\UBAID ULLAH\Documents\Visual Studio 2012\Projects\Backup MDFData\MDFData\AdminToolForm.cs:line 79
有什么建议吗?
【问题讨论】:
-
您确实需要考虑使用 SQL 参数。您的代码,特别是考虑到这是关于密码散列的代码,非常不安全。
-
password和login_name都是字符串吗?您是否尝试将列名括在方括号中,以防它们与保留名称发生冲突? -
尝试在列名周围添加方括号。
[password]和[login_name] -
@James:让我试试。
-
@James:你说得很对。谢谢你拯救了我的一天。请将其发布为答案,以便我接受它作为解决方案。
标签: c# visual-studio oledb