sql查询类问题在c#上使用sqlite

本文关键字:sqlite 查询 问题 sql | 更新日期: 2023-09-27 17:49:58

我在c#上使用SQLite提供程序。我试图使用SQL select * from table where name like 'part_of_name%'。但是这个查询不能正确工作。调试写入System.InvalidOperationException in application System.Data.SQLite.dll

的例子:我有表Books(id, name)有3个项目:

  1. 《哈利波特与魔法石》
  2. 《哈利波特与密室》

在SQLite管理器查询select * from Books where name like 'Harry%'显示我1-st和2-nd项,但在我的c#应用程序中只有1-st和调试异常。当我尝试... like '%'时,我的应用程序只显示我第一个项目,但当我尝试... like 'God%'时,它显示我第三个项目。请帮帮我。谢谢!这是代码:

sqliteConn.Open(); //open connection
sqliteDA.SelectCommand = new SQLiteCommand("select * from Books where name like '" + text + "%'", sqliteConn); //create SQL-query in sqlite data adapter
dataSet.Tables["Books"].Clear(); //clear our dataset.table with old info
sqliteDA.Fill(dataSet, "Books"); //fill our dataset.table with info from sqlite data adapter
sqliteConn.Close(); //close connection

sql查询类问题在c#上使用sqlite

您应该使用参数并对参数值应用%。试试这样做,让我知道它是否有效:

SQLiteCommand cmd = new SQLiteCommand("select * from Books where name like @name", sqliteConn); 
cmd.Parameters.AddWithValue("@name", string.Concat(text, "%"));
sqliteDA.SelectCommand = cmd;
DataTable dataTable = new DataTable();
sqliteDA.Fill(dataTable); //just a DataTable instance