[英]Bulk Copy C# to PostgreSql
我有一个包含1000条记录的数据表。 我想执行从C#到PGSQL的批量插入操作。 我知道一种将文本文件复制到pgtable
。
示例语法如下:
using (NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;Password=postgres;Database=postgres;"))
{
onn.Open();
NpgsqlCommand command = new NpgsqlCommand("copy \"schema\".\"tablename\" (\"col1\",\"col2\") from 'C:\\datafile.txt'", conn);
command.ExecuteNonQuery();
conn.Close();
}
我还有其他函数可以用来传递数据表,而不是将数据写入文本文件吗? 我正在使用Npgsql.dll
。
您可能应该完整阅读PostgreSQL文档COPY 。
COPY可以用于导入PostgreSQL服务器文件系统中存在的文件(如您的代码示例所示),也可以用于从客户端复制数据,这可能正是您想要的。 后者是通过用STDIN
代替文件名来触发的。
如果要使用Npgsql从客户端程序导入数据,请也阅读Npgsql COPY文档 。 对于文本数据导入,您可能需要调用NpgsqlConnection.BeginTextImport()
,在文档中有一个示例。
public bool CopyFileToPostgress(String tableName, String filePath,String delimiter)
{
NpgsqlConnection conn = new NpgsqlConnection("Host=xx.xx.xx.xx;port=xxxx;Database=xxxx;Username=xxxx;Password=xxxx;Pooling=false;Timeout=300;CommandTimeout=300");
NpgsqlCommand cmd = new NpgsqlCommand();
Boolean result = true;
try
{
conn.Open();
NpgsqlTransaction transaction = conn.BeginTransaction();
if (File.Exists(filePath))
{
try
{
NpgsqlCommand command = new NpgsqlCommand($"COPY {tableName} FROM '{filePath}' (DELIMITER '{delimiter}')", conn);
command.ExecuteNonQuery();
}
catch (Exception e)
{
result = false;
transaction.Rollback();
throw e;
}
finally
{
if (result)
{
transaction.Commit();
}
transaction.Dispose();
}
}
}
catch (Exception ex)
{
result = false;
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.