c# - OleDb 异常

标签 c# ms-access oledb oledbexception

搜索了 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/

相关文章:

c# - 查明字符串列表项是否以另一个列表中的另一个项目开头

c# - Protocol Buffer 从原始消息中检测类型

sql-server - 使用架构和表更改将数据从 MS Access 导出到 MS SQL

sql-server - 尝试在 SSIS 中导入 Excel 文件时出现 "External table is not in the expected format."错误

c# - 64 位模式不支持 OleDB?

javascript - 使用 System.IdentityModel.Tokens.Jwt 验证在 C# 中生成的 token

c# - 为什么 is 关键字需要非空表达式?

c# - 我的应用程序和 Access 查询向导之间的不同 LIKE 行为

sql - 如何使用 SQL 识别或识别数据中的模式

c# - Windows 搜索查询文件内容中单词/子字符串的*部分*