SQLite预处理语句在SQLiteDataReader上无法正常工作?

3

以下是我的代码

SQLiteConnection connection = new SQLiteConnection("Data Source=userData.dat;version=3;");
connection.Open();

SQLiteCommand cmd = connection.CreateCommand();

cmd.CommandText = "SELECT * FROM tags WHERE tags_tags LIKE '%@tags_tags%' ORDER by tags_id DESC LIMIT 0, 100";
cmd.Parameters.Add("@tags_tags", DbType.String);
cmd.Parameters["@tags_tags"].Value = tags;


SQLiteDataReader reader = cmd.ExecuteReader();
var _sql = cmd.CommandText;
MessageBox.Show(_sql);//still shows "SELECT * FROM tags WHERE tags_tags LIKE '%@tags_tags%' ORDER by tags_id DESC LIMIT 0, 100"

我也使用了 cmd.Parameters.AddWithValue,但没有起作用...错误在哪里?

你有尝试过使用try-catch捕获异常吗? - KMC
没有任何错误。唯一的问题是我的查询仍未准备好。 - Soroush Khosravi
你无法在命令文本中看到替换变量后的完整查询。你需要启动SQL Profiler并记录发送到服务器的查询。在那里,你将获得完全相同的查询,但也包括定义的变量。 - KeepAlive
1个回答

3

将参数连接到你的字符串中,例如:

LIKE '%' || @tags_tags || '%'

您正在使用单引号将参数括起来,从而使其成为一个值。删除单引号,并在参数值上连接百分号。

LIKE @tags_tags

在你的参数中,
cmd.Parameters["@tags_tags"].Value = '%' + tags + '%';

非常非常非常好!这正是我想要的 :x - Soroush Khosravi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接