c# - SQLite 从数据表中插入

标签 c# sqlite

使用下面的代码,我得到了查询的@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();

最佳答案

您不能将 DataTable 作为参数传递。 我认为你想使用 DataTable 作为参数的主要原因是你想在 sqlite 中批量插入。这是一个例子

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

Reference: Bulk Insert in Microsoft.Data.Sqlite

关于c# - SQLite 从数据表中插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696547/

相关文章:

c# - 将字符串数组传递给 webservice 方法

c# - 解析 RegEx 模式

c# - Android App - Xamarin - C# - 如何将多个整数变量值返回到主要 Activity ?

Android:在显示之前对Cursor中的SQL返回值进行算术

macos - 如何在 OS X 上部署使用 SQLite 的 Qt 应用程序

c# - 在没有第 3 方框架的情况下实现 DI

c# - Json.net 将数字属性序列化为字符串

java - 使用预填充信息创建表时出现 SQLITE 数据库错误(表有 3 列,但提供了 2 个值)

Python+sqlite : the LIKE query with wildcards

python - Sqlite3数据库Python条件语句