首页 > 解决方案 > 从数据表插入 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();

标签: c#sqlite

解决方案


您不能将 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();
}

参考:Microsoft.Data.Sqlite 中的批量插入


推荐阅读