如何使用SQLiteCommand进行插入查询?

时间:2017-11-10 21:38:36

标签: c# sqlite

我有一段代码,总是对我不起作用。有时它会返回有关数据库锁定的错误,有时会返回连接。

这是代码:

string sql = String.Format("insert into {0}({1}) values({2});", tableName, columns, values);
SQLiteConnection myConn = null;
try 
{
    myConn = new SQLiteConnection(dbConnection);
    myConn.Open();

    using(SQLiteCommand sqCommand = new SQLiteCommand(sql))
    {
        sqCommand.CommandText = sql;
        int rows = sqCommand.ExecuteNonQuery();
        return !(rows == 0);
    }
} 
finally 
{
    myConn.Close();
}

我做错了什么?

错误是:

  

没有与此命令关联的连接

   в System.Data.SQLite.SQLiteCommand.InitializeForReader()
   в System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior
     

行为)          System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior   行为)          System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()

排队:

int rows = sqCommand.ExecuteNonQuery();

1 个答案:

答案 0 :(得分:2)

您忘了assign ConnectionCommand

  

没有与此命令关联的连接

using(SQLiteCommand sqCommand = new SQLiteCommand(sql))
因此

应该是:

using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn))
相关问题