从数据表插入SQLite

3

使用以下代码时,@table 部分的查询会引发异常。你能否使用数据表以这种方式插入 SQLite 中?

 DataTable table = new DataTable();
 table.Columns.Add("Path", typeof(string));
 table.Columns.Add("StopName", typeof(string));
 table.Columns.Add("Latitude", typeof(string));
 table.Columns.Add("Longitude", typeof(string));

 foreach (Result result in tempResults)
 {
      table.Rows.Add(result.Path, result.StopName, result.Latitude, result.Longitude);
 }

 SQLiteCommand command = new SQLiteCommand("INSERT OR REPLACE INTO ZZ_DBA_Stop (Path, StopName, Latitude, Longitude) SELECT Path, StopName, Latitude, Longitude FROM @table", connection) { CommandTimeout = 3600, CommandType = CommandType.Text };
 command.Parameters.AddWithValue("@table", table);
 await command.ExecuteNonQueryAsync();

4
不,参数不能用于FROM参数。无论如何,您不能传递一个DataTable并希望它被用于插入到数据库表中。 - Steve
2个回答

2

您无法将DataTable作为参数传递。

我认为您想使用DataTable作为参数的主要原因是要在SQLite中进行批量插入。以下是一个示例:

Original Answer翻译成"最初的回答"

using (var transaction = connection.BeginTransaction())
using (var command = connection.CreateCommand())
{
    command.CommandText =
        "INSERT INTO contact(name, email) " +
        "VALUES($name, $email);";

    var nameParameter = command.CreateParameter();
    nameParameter.ParameterName = "$name";
    command.Parameters.Add(nameParameter);

    var emailParameter = command.CreateParameter();
    emailParameter.ParameterName = "$email";
    command.Parameters.Add(emailParameter);

    foreach (var contact in contacts)
    {
        nameParameter.Value = contact.Name ?? DBNull.Value;
        emailParameter.Value = contact.Email ?? DBNull.Value;
        command.ExecuteNonQuery();
    }

    transaction.Commit();
}

最初的回答:

参考:在Microsoft.Data.Sqlite中进行批量插入


0

很遗憾,参数不能用于表示表或列的名称。您只能使用它们来表示WHERE语句中的值或UPDATE / INSERT / DELETE操作中的值。

因此,您应该逐个插入记录,或编写支持批量更新的代码,如this question所述。

但是,如果您想尝试非常有用的第三方库,可以编写非常简单的代码。

此示例使用Dapper完成

NuGet
Project Site

using(SQLiteConnection connection = GetOpenedConnection())
{
    string cmdText = @"INSERT OR REPLACE INTO ZZ_DBA_Stop 
                      (Path, StopName, Latitude, Longitude) 
                      VALUES(@Path, @StopName, @Latitude, @Longitude) ";
    connection.ExecuteAsync(cmdText, tempResults);
}

Dapper是一个简单的ORM(对象关系映射)工具,它扩展了IDbConnection的功能。它知道如何处理你的模型,并从数据库中存储和检索数据。
在上面的示例中,你将整个列表作为第二个参数传递给ExecuteAsync方法,Dapper会帮助你将整个列表的数据插入到数据库中。唯一的要求是你的模型属性必须与字段名称相同。

GetOpenedConnection只是一个返回已打开的SQLiteConnection的方法的占位符。你可以用创建连接所需的代码替换它,并在调用ExecuteAsync之前添加打开连接的调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接