【问题标题】:SQLiteDataReader error, near "table": syntax errorSQLiteDataReader 错误,靠近“表”:语法错误
【发布时间】:2017-08-20 12:00:46
【问题描述】:

我的 C# 项目中有简单的 SQLite 数据库表 Database Screenshot

这是我用来从数据库中检索数据的代码:

SQLiteConnection dbConnection;
dbConnection = new SQLiteConnection("Data Source=./new.db;");
dbConnection.Open();
if (dbConnection.State == System.Data.ConnectionState.Open)
     richTextBox3.Text = "Conn";
string sqlcommand = "SELECT age FROM table WHERE index=1";
SQLiteCommand command = new SQLiteCommand(sqlcommand, dbConnection);
SQLiteDataReader result = command.ExecuteReader();
if(result.HasRows)
{
      while (result.Read())
      {
           richTextBox1.Text = result.GetInt32(0) + " "+ result.GetString(1) + " " + result.GetInt32(2);
       }
 }

也许while循环不正确,但我的问题是表格附近的语法错误。

【问题讨论】:

  • table 是一个关键字,你必须使用你的表名(除了表词)来代替表词..
  • 循环也不起作用。在循环中,您在索引 0、1、2 处请求 3 个字段,但您的选择只有一个字段。这将在索引 0 处可用。请求索引 1 和 2 将导致 IndexOutOfRange 异常

标签: c# sqlite


【解决方案1】:

@Rohit 提到 table 是 SQLite 中的一个关键字,但如果您仍想使用它,您可以更改您的查询,如下所示: 用[table]包围你的表名

string sqlcommand = "SELECT age FROM [table] WHERE index=1";

它也适用于SQLSERVER

【讨论】:

    【解决方案2】:

    尝试在表之间添加``,因为表是保留字。您可以在reserved words查看所有保留字

    string sqlcommand = "SELECT `age` FROM `table` WHERE `index`='1'";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-18
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多