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

标签 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();
}

我做错了什么?

错误是:

No connection associated with this command

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

behavior) в System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior) в System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()

行内:

int rows = sqCommand.ExecuteNonQuery();

最佳答案

你忘了assign 连接命令:

No connection associated with this command

using(SQLiteCommand sqCommand = new SQLiteCommand(sql))

因此应该是:

using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn))

关于c# - 如何使用SQLiteCommand进行插入查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47231521/

相关文章:

c# - 我如何创建两个部分来重点关注和其他部分进行写作?

c# - 通过 Windows Azure 发布后无法加载文件或程序集 System.Runtime.Serialization

c# - 要求所有参数和所有参数命名的类构造函数

生产环境中的 python 和 SQLite

c# - 如何在不使用 ZipArchive 的情况下在 Windows 8 Metro 中解压缩 ZIP 文件 (zlib.net)

c# - ajax使用处理程序请求到 Razor 页面

java - Sqlite 数据库未使用 java 更新

python - 如何更新最新的sqlite3帖子?

sqlite - SQLite 中的 UTC 时间错误

android - 如何使用SELECT SQLite语句并将数据输出为字符串?