27/7/05

Código C# para postgress

Hace falta el Postgres .Net Data Provider (proyecto libre por la 0.7)
Ojo. Los nombres de todo en la definición de las tablas han de estar en minúsculas. El postgres permite ponerlas diferenciando pero el .net data provider se lía si hay mayusculas.

NpgsqlConnection oCn=new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=popo;Database=prueba1;");
try
{
string strSQL=string.Empty;
oCn.Open();

strSQL="SELECT max(Cod) FROM pru2";
NpgsqlCommand oCmd=new NpgsqlCommand(strSQL,oCn);
int auxCod = Convert.ToInt32(oCmd.ExecuteScalar()) + 1;

strSQL=String.Format("insert into pru2(cod,nomb) values ({0},'{0}')",auxCod.ToString());
MessageBox.Show(strSQL);
oCmd=new NpgsqlCommand(strSQL,oCn);
oCmd.ExecuteNonQuery();

strSQL=String.Format("update pru2 set cod = {0}, nomb = '{0}'",auxCod.ToString());
oCmd=new NpgsqlCommand(strSQL,oCn);
oCmd.ExecuteNonQuery();


// falta un borrado (delete)

strSQL="SELECT Cod , Nomb FROM pru2";
oCmd=new NpgsqlCommand(strSQL,oCn);
NpgsqlDataReader oReader=oCmd.ExecuteReader();
if (oReader.HasRows==true)
{
while (oReader.Read())
{
Console.WriteLine(String.Format("Empleado {0} - {1}",oReader[0].ToString(),oReader[1].
ToString()));
}
oReader.Close();oReader.Dispose();oReader=null;oCmd.Dispose();oCmd=null;
}
else
{
Console.WriteLine("No Existen registros....");
}
Console.ReadLine();

}
catch (NpgsqlException oErrorPostgreSQL)
{
Console.WriteLine(oErrorPostgreSQL.Message);
}
catch (Exception oError)
{
Console.WriteLine(oError.Message);
}
finally
{
oCn.Close();oCn.Dispose();oCn=null;
}