I wanted to execute my reader for Npgsql query but there's an error stated like this:
'NpgsqlBatchCommand' does not contain a definition for 'Connection' and no accessible extension method 'Connection' accepting a first argument of type 'NpgsqlBatchCommand' could be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]
&
'NpgsqlBatchCommand' does not contain a definition for 'ExecuteReader' and no accessible extension method 'ExecuteReader' accepting a first argument of type 'NpgsqlBatchCommand' could be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]
Anyone knows why? Or does it have a new function or got deleted for version 6.0.5???
Here's my code:
using Npgsql;
void Start()
{
using(NpgsqlConnection conn = new NpgsqlConnection())
{
conn.ConnectionString = "Server = localhost; Port = 5433; Database =
Postgres2; User Id = postgres; Password = admin";
try
{
NpgsqlBatchCommand cmd = new NpgsqlBatchCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id FROM m_pasukan";
cmd.Connection = conn;
conn.Open();
Debug.Log("Connection Open!");
NpgsqlBatchCommand sdr = cmd.ExecuteReader();
while(sdr.Read())
{
int id = (int)sdr["id"];
Debug.Log(id);
}
}
catch(Exception ex)
{
Debug.Log("Cannot Open Connection!!");
}
}
}
They aren't gone. The wrong class is used. The code uses NpgsqlBatchCommand instead of NpgsqlCommand. The class that derives from ADO.NET's DbCommand base class and implements the IDbCommand interface is NpgsqlCommand, not NpgsqlBatchCommand.
Your code should be :
var cmd = new NpgsqlCommand();
or even :
using(var cmd=new NpgsqlCommand())
{
...
}
or
using(var cmd=new NpgsqlCommand(sql,conn))
{
...
}
ExecuteReader returns a DbDataReader that needs to be disposed too. A DbDataReader is a fast-forward cursor over the query results that consumes both client and server resources :
using(var sdr = cmd.ExecuteReader())
{
...
}