我正在尝试使用SQLite作为我的存储空间.我已经使用nuget和using语句添加了引用dll.
我有
private void SetConnection()
{
sql_con = new SQLiteConnection
("Data Source=c:\\Dev\\MYApp.sqlite;Version=3;New=False;Compress=True;");
}
private void ExecuteQuery(string txtQuery)
{
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
sql_cmd.CommandText = txtQuery;
sql_cmd.ExecuteNonQuery();
sql_con.Close();
}
Run Code Online (Sandbox Code Playgroud)
我正在发送这样的查询文本
public void Create(Book book)
{
string txtSqlQuery = "INSERT INTO Book (Id, Title, Language, PublicationDate, Publisher, Edition, OfficialUrl, Description, EBookFormat) ";
txtSqlQuery += string.Format("VALUES (@{0},@{1},@{2},@{3},@{4},@{5},@{6},@{7},{8})",
book.Id, book.Title, book.Language, book.PublicationDate, book.Publisher, book.Edition, book.OfficialUrl, book.Description, book.EBookFormat);
try
{
ExecuteQuery(txtSqlQuery);
}
catch (Exception ex )
{
throw new Exception(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
我的数据库正确创建并传递了具有有效数据的书籍实例.但是在这行代码上执行查询总是抛出异常:
sql_cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)
我显然在这里做错了但我看不到.
更新:抛出异常消息是
SQL逻辑错误或缺少数据库
无法识别的令牌:"22cf"
这22cf是传递book.Idguid字符串的一部分.
LS_*_*ᴅᴇᴠ 50
使用预准备语句和绑定参数:
public void Create(Book book) {
SQLiteCommand insertSQL = new SQLiteCommand("INSERT INTO Book (Id, Title, Language, PublicationDate, Publisher, Edition, OfficialUrl, Description, EBookFormat) VALUES (?,?,?,?,?,?,?,?,?)", sql_con);
insertSQL.Parameters.Add(book.Id);
insertSQL.Parameters.Add(book.Title);
insertSQL.Parameters.Add(book.Language);
insertSQL.Parameters.Add(book.PublicationDate);
insertSQL.Parameters.Add(book.Publisher);
insertSQL.Parameters.Add(book.Edition);
insertSQL.Parameters.Add(book.OfficialUrl);
insertSQL.Parameters.Add(book.Description);
insertSQL.Parameters.Add(book.EBookFormat);
try {
insertSQL.ExecuteNonQuery();
}
catch (Exception ex) {
throw new Exception(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
Izi*_*kon -4
将字符串发送到 INSERT 语句 VALUES 时应使用 (') (@{0},'@{1}','@{2}','@{3}','@{4}','@{ 5}','@{6}','@{7}',{8}) 您还应该捕获 SQLExeprion