搜索了 5 个小时,我找不到我的错误。我得到这个异常(exception)。怎么了?
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in MyDictionary.exe
Additional information: Syntax error in INSERT INTO statement.
我的代码:
public void Insert(Word word)
{
string language=FindLanguage();
try
{
command.CommandText ="INSERT INTO "+language+" ( Native , Foreign , Definition , AddingDate) values ( '" + word.Native + "' , '" + word.Foreign + "' , '" + word.Definition + "' ,'" + word.AddingDate + "')";
command.CommandType = System.Data.CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
最佳答案
您应该在插入语句中使用参数。看起来您还缺少 command.Connection = connection;
。
请注意,您的 SQL 很容易出现 SQL Injection
command.CommandText ="INSERT INTO "+language+"([Native],[Foreign],[Definition],[AddingDate]) VALUES (@Native,@Foreign,@Definition,@AddingDate)";
command.Parameters.AddWithValue("@Native", word.Native);
command.Parameters.AddWithValue("@Foreign",word.Foreign);
command.Parameters.AddWithValue("@Definition",word.Definition);
command.Parameters.AddWithValue("@AddingDate",word.AddingDate);
command.CommandType = System.Data.CommandType.Text;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
关于c# - OleDb 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38509044/