【问题标题】:InvalidCastException: Cannot Cast from source type to destination type. sqliteInvalidCastException:无法从源类型转换为目标类型。 sqlite
【发布时间】:2017-05-20 18:41:01
【问题描述】:

我正在尝试从 sqlite 表中获取数据并统一使用它。 这是我的代码

string conn = "URI=file:DB.db"; //Path to database.
    IDbConnection dbconn;
    dbconn = (IDbConnection)new SqliteConnection(conn);
    try
    {
        dbconn.Open(); //Open connection to the database.

    }
    catch (Exception ex)
    {
        throw ex;
    }

    IDbCommand dbcmd = dbconn.CreateCommand();
    string sqlQuery = "SELECT * FROM mytable WHERE id =" + LevelID + "";
    dbcmd.CommandText = sqlQuery;
    IDataReader reader = null;
    reader = dbcmd.ExecuteReader();

    if (reader != null)
    {
        while (reader.Read())
        {
           string question = reader.GetString(0);
           string cat = reader.GetString(1);
         }
      }

我得到的例外:

InvalidCastException: Cannot cast from source type to destination type.
Mono.Data.Sqlite.SqliteDataReader.VerifyType (Int32 i, DbType typ)
Mono.Data.Sqlite.SqliteDataReader.GetString (Int32 i)

我检查了数据库,该字段是“TEXT”,其中存储的数据是一个字符串,我声明的是字符串,那为什么它说它是 Int 呢?

【问题讨论】:

    标签: c# sqlite unity3d


    【解决方案1】:

    避免使用SELECT * FROM mytable,但尝试更明确地说明您选择的内容。例如,改为这样编写查询:

    SELECT NameOfColumn1, NameOfColumn2, ... FROM mytable
    

    Select * 选择的列可能多于您预期的 2 列(如果您的表有更多列,它将选择所有列)。因此,铸件正在破裂。

    【讨论】:

    • 谢谢。我使用的是第二列(即 Int)而不是第三列(即 string)。将我的代码更改为:string cat = reader.GetString(2); 解决了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多