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();
}
推荐阅读
- linux-device-driver - tty 默认 fops 和驱动程序特定 fops
- node.js - 如何防止移动网络浏览器超时?我想让客户端连接到 socket.io 服务器
- javascript - 有什么方法可以将自定义数据从 Revit 传输到 Viewer?
- php - Laravel 动态获取复选框值
- sql - 根据字符串中的序列分配字符串 - Oracle SQL
- protractor - 需要帮助在代码中设置 protractor.browser
- kubernetes - 如何配置 kubernetes_sd_configs 以发现不同集群中的服务
- java - 如何使用动态字段围绕枚举创建包装类
- c# - 从 PictureBox 保存图像
- database - 根据两行之间的差异选择列