使用此查询时出现 SQL 语法错误

I get an SQL syntax error when using this query

这个有效:

 string sqlStr = string.Format("INSERT INTO tblFiles (filename,downloadname,description,category,length,parts,checksum,isEncrypted,uploaderIp) VALUES ('{0}','{1}','{2}','{3}',{4},{5},'{6}',{7},'{8}');",
            newFile.Name.Replace("'", "''"), newFile.DownloadName.Replace("'", "''"), newFile.Description, newFile.Category, newFile.Length, newFile.Parts, newFile.Checksum, newFile.IsEncrypted, GetPeerIp());

这不是:

string sqlStr = string.Format("INSERT INTO tblFiles (filename,downloadname,description,category,length,parts,checksum,isEncrypted,password,uploaderIp) VALUES ('{0}','{1}','{2}','{3}',{4},{5},'{6}',{7},'{8}','{9}');",
        newFile.Name.Replace("'", "''"), newFile.DownloadName.Replace("'", "''"), newFile.Description, newFile.Category, newFile.Length, newFile.Parts, newFile.Checksum, newFile.IsEncrypted, password, GetPeerIp());

我得到异常:

$exception {"Syntax error in INSERT INTO statement."} System.Exception {System.Data.OleDb.OleDbException}

我的数据库是这样的。

我找不到任何问题。有任何想法吗? 谢谢

密码是 MS-Access 中的保留关键字 sql。如果您有一个具有该名称的字段,您需要将该名称封装在方括号之间(最好现在更改它)

string sqlStr = @"INSERT INTO tblFiles 
   (filename,downloadname,description,category,length,parts,
   checksum,isEncrypted,[password],uploaderIp) VALUES (.....)";

说,请删除所有字符串连接并使用参数化查询。这不仅更安全(防止 Sql 注入)而且还消除了引用和正确解析日期和小数的所有问题

string sqlStr = @"INSERT INTO tblFiles 
   (filename,downloadname,description,category,length,parts,
   checksum,isEncrypted,[password],uploaderIp) VALUES 
   (@file, @down, @desc, @cat, @len, @parts, @check, @enc, @pass, @up)";

OleDbCommand cmd = new OleDbCommand(sqlStr, connection);
cmd.Parameters.Add("@file", OleDbType.VarWChar).Value = newFile.Name;
cmd.Parameters.Add("@down", OleDbType.VarWChar).Value = newFile.DownloadName;
... and so on for all other parameters respecting the OleDbType of the column....

cmd.ExecuteNonQuery();

请注意您的查询如何更加清晰易懂,以及您如何不需要调用大量 Replace 来去除可能的嵌入式单引号。