Npgsql:如何准备语句

时间:2010-12-10 02:23:08

标签: c# performance postgresql prepared-statement npgsql

我们正在为多人游戏开发数据库后端。服务器是用C#编写的,并通过Npgsql与Postgres数据库进行通信。

现在,手册显示了如何使用预准备语句:

NpgsqlCommand command = new NpgsqlCommand("select * from tablea where column1 = :column1", conn);
// Now add the parameter to the parameter collection of the command specifying its type.
command.Parameters.Add(new NpgsqlParameter("column1", NpgsqlDbType.Integer);
// Now, prepare the statement.
command.Prepare();
// Now, add a value to it and later execute the command as usual.
command.Parameters[0].Value = 4;

它声明预准备语句仅在数据库会话中有效。 我现在有两个问题:

1。)如果我使用相同的命令文本和参数类型创建新的NpgsqlCommand对象,服务器是否会识别此命令已准备好,或者我是否必须保留该对象并在再次执行之前更改变量?在示例中,命令对象在查询之后被释放。

2。)准备好的语句可能会提高性能,尽管我们只有这种风格的简单陈述:

SELECT f1,f2 FROM t1
UPDATE t1 SET f1=1, f2=2

有可能连续执行数百个具有相同样式的查询 - 当前为每个查询创建一个新的NpgsqlCommand(以及来自NpgSql池的NpgsqlConnection)对象。

谢谢!

1 个答案:

答案 0 :(得分:2)

我建议你不要使用准备好的陈述。 Npgsql还没有很好的性能。 :(对不起。

另外,为了发送大量的insert命令,我认为你应该看一下NpgsqlCopy的支持。它会给你一个更好的表现。 我希望它有所帮助。