1
USING NPGSQL
Npgsql is a .Net Data Provider for Postgresql. It allows any program developed for .Net
framework to access database server. It is implemented in 100% C# code. Works with Postgresql 7.x
and above.
String Code
using Npgsql;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User
Id=postgres;Password=admin;Database=XXXXXX;");
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
Npgsql;
Open Connect
Close Connect
const string pgConstring = "Server=localhost;port=5432;Database=postgres;User
id=postgres;Password=159753;";
NpgsqlConnection conn = new NpgsqlConnection(pgConstring);
conn.Open();
public void OpenConn()
{
try
{
conn.Open();
}
catch (Exception exp)
{
MessageBox.Show("Error :S");
}
}
public void CloseConn()
{
try
{
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Error :S");
}
}
Insert
public void InsertOnTable(Object objGen)
{
try
{
this.OpenConn();
// Get type and properties (vector)
Type typeObj = objGen.GetType();
PropertyInfo[] properties = typeObj.GetProperties();
// Get table
string[] type = typeObj.ToString().Split('.');
string table = type[2].ToLower();
// Start mounting string to insert
string SQL = "INSERT INTO " + table + " VALUES (";
// It goes from second until second to last
for (int i = 1; i < properties.Length - 1; i++)
{
object propValue = properties[i].GetValue(objGen, null);
string[] typeValue =
propValue.GetType().ToString().Split('.');
if (typeValue[1].Equals("String"))
{
SQL += "'" + propValue.ToString() + "',";
}
else if (typeValue[1].Equals("DateTime"))
{
SQL += "'" +
Convert.ToDateTime(propValue.ToString()).ToShortDateString() + "',";
}
else
{
SQL += propValue.ToString() + ",";
}
}
// get last attribute here
+ "'";
object lastValue = properties[properties.Length - 1].GetValue(objGen, null);
string[] lastType = lastValue.GetType().ToString().Split('.');
if (lastType[1].Equals("String"))
{
SQL += "'" + lastValue.ToString() + "'";
}
else if (lastType[1].Equals("DateTime"))
{
SQL += "'" + Convert.ToDateTime(lastValue.ToString()).ToShortDateString()
}
else
{
SQL += lastValue.ToString();
}
// Ends string builder
SQL += ");";
// Execute command
NpgsqlCommand command = new NpgsqlCommand(SQL, conn);
Int32 rowsaffected = command.ExecuteNonQuery();
this.CloseConn();
}
catch (Exception)
{
MessageBox.Show("Errr on insert!");
}
Update
public void UpdateOnTable(Object objGen, int idValue)
{
try
{
this.OpenConn();
// Get table
string[] type = objGen.GetType().ToString().Split('.');
string table = type[2].ToLower();
// Start building
string SQL = "UPDATE " + table + " SET ";
// Get types and properties
Type type2 = objGen.GetType();
PropertyInfo[] properties = type2.GetProperties();
// Goes until second to last
for (int i = 0; i < properties.Length - 1; i++)
{
object propValue = properties[i].GetValue(objGen, null);
string[] nameAttribute = properties[i].ToString().Split(' ');
string[] typeAttribute = propValue.GetType().ToString().Split('.');
if (typeAttribute[1].Equals("String"))
{
SQL += nameAttribute[1] + " = '" + propValue.ToString() + "',";
}
else if (typeAttribute[1].Equals("DateTime"))
{
SQL += nameAttribute[1] + "= '" +
Convert.ToDateTime(propValue.ToString()).ToShortDateString() + "',";
}
else
{
SQL += nameAttribute[1] + " = " + propValue.ToString() + ",";
}
}
');
// Process last attribute
object lastValue = properties[properties.Length - 1].GetValue(objGen, null);
string[] lastType = lastValue.GetType().ToString().Split('.');
string[] ultimoCampo = properties[properties.Length - 1].ToString().Split('
if (lastType[1].Equals("String"))
{
SQL += ultimoCampo[1] + " = '" + lastValue.ToString() + "'";
}
else if (lastType[1].Equals("DateTime"))
{
SQL += ultimoCampo[1] + "= '" +
Convert.ToDateTime(lastValue.ToString()).ToShortDateString() + "'";
}
else
{
SQL += ultimoCampo[1] + " = " + lastValue.ToString();
}
// Ends string builder
SQL += " WHERE id = " + idValue + ";";
// Execute query
NpgsqlCommand command = new NpgsqlCommand(SQL, conn);
Int32 rowsaffected = command.ExecuteNonQuery();
this.CloseConn();
}
catch (Exception)
{
MessageBox.Show("Errr on update!");
}
}
Delete
public void DeleteOnTable(Object objGen, int idValue)
{
try
{
this.OpenConn();
string[] type = objGen.GetType().ToString().Split('.');
string table = type[2];
string SQL = "DELETE FROM " + table + " WHERE id = " + idValue + ";";
NpgsqlCommand command = new NpgsqlCommand(SQL, conn);
Int32 rowsaffected = command.ExecuteNonQuery();
this.CloseConn();
}
catch (Exception)
{
MessageBox.Show("Errr on update!");
}
}
Querying everything
public ListObject QueryAllOnTable(string table)
{
try
{
this.OpenConn();
ListObject lstSelect = new ListObject();
string SQL = "SELECT * FROM " + table + ";";
NpgsqlCommand command = new NpgsqlCommand(SQL, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
lstSelect.Add(dr[i]);
}
}
this.CloseConn();
return lstSelect;
}
catch (Exception)
{
MessageBox.Show("Errr on query!");
return null;
}
}
Querying
public ListObject QueryOnTableWithParams(string table, string[] paramName, string[]
paramValue)
{
try
{
if (paramName.Count != paramValue.Count)
{
MessageBox.Show("Wrong number of params");
return null;
}
this.OpenConn();
ListObject lstSelect = new ListObject();
string SQL = "SELECT * FROM " + table + " WHERE ";
// get params
for (int i = 0; i < paramName.Count - 1; i++)
{
SQL += paramName[i] + " = " + paramValue[i] + " AND ";
}
// get last param
SQL += paramName[paramName.Count - 1] + " = " + paramValue[paramValue.Count 1] + ";";
NpgsqlCommand command = new NpgsqlCommand(SQL, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
lstSelect.Add(dr[i]);
}
}
this.CloseConn();
return lstSelect;
}
catch (Exception)
{
MessageBox.Show("Errr on query!");
return null;
}
}
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;" +
"Password=pwd;Database=postgres;");
conn.Open();
public void InitializeComponent()
{
this.ClientSize = new System.Drawing.Size(640, 400);
npgridfrm = new DataGrid();
npgridfrm.Location = new Point(10, 10);
npgridfrm.Size = new Size(620, 350);
this.Text = "Simple example of data grid by Npgsql";
this.Controls.Add(npgridfrm);
ok = new Button();
ok.Location = new Point(10, 365);
ok.Size = new Size(70, 25);
ok.TabIndex = 1;
ok.Text = "&Ok";
this.Controls.Add(ok);
ok.Click += new System.EventHandler(button_Click);
tipok = new ToolTip();
tipok.SetToolTip(ok, "Updated refreshing");
exit = new Button();
exit.Location = new Point(95, 365);
exit.Size = new Size(70, 25);
exit.TabIndex = 1;
exit.Text = "&Exit";
this.Controls.Add(exit);
exit.Click += new System.EventHandler(button_Click);
tipexit = new ToolTip();
tipexit.SetToolTip(exit, "End of this program");
ConnectToData();
// Here we connect Npgsql datasource "dtsource" created in previous method
with our form.
try
{
npgridfrm.DataSource = dtsource;
npgridfrm.SetDataBinding(dset, "npdata");
dtsource.RowChanged += new DataRowChangeEventHandler(Row_Changed);
}
catch (Exception ex) { }
}
// This method is responsible to get the data from server and
// setup delete, update and insert commands for table.
public void ConnectToData()
{
string DSN;
Npgsql.Design.ConnectionStringEditorForm Ndesign = new
Npgsql.Design.ConnectionStringEditorForm();
Ndesign.ShowDialog();
DSN = Ndesign.ConnectionString.ToString();
if (DSN == "")
return;
conn = new NpgsqlConnection(DSN);
dset = new DataSet("npdata");
NpAdapter = new NpgsqlDataAdapter();
NpAdapter.SelectCommand = new NpgsqlCommand(query, conn);
NpAdapter.Fill(dset, "npdata");
dtsource = dset.Tables["npdata"];
deleteCmd();
updateCmd();
insertCmd();
}
// Setups the delete command.
public void deleteCmd()
{
string query = "DELETE FROM npdata WHERE key = @key";
NpAdapter.DeleteCommand = new NpgsqlCommand(query, conn);
NpParam = NpAdapter.DeleteCommand.Parameters.Add("@key",
NpgsqlTypes.NpgsqlDbType.Text);
NpParam.SourceColumn = "key";
NpParam.SourceVersion = DataRowVersion.Original;
}
// Setups the update command.
public void updateCmd()
{
string query = "UPDATE npdata SET key = @key, ndata = @ndata WHERE key =
@key";
NpAdapter.UpdateCommand = new NpgsqlCommand(query, conn);
NpParam = NpAdapter.UpdateCommand.Parameters.Add("@key",
NpgsqlTypes.NpgsqlDbType.Text);
NpParam.SourceColumn = "key";
NpParam.SourceVersion = DataRowVersion.Original;
NpParam = NpAdapter.UpdateCommand.Parameters.Add("@ndata",
NpgsqlTypes.NpgsqlDbType.Bigint);
NpParam.SourceVersion = DataRowVersion.Current;
NpParam.SourceColumn = "ndata";
}
// Setups the insert command.
public void insertCmd()
{
string insertQuery = "INSERT INTO npdata VALUES (@key, @ndata)";
NpAdapter.InsertCommand = new NpgsqlCommand(insertQuery, conn);
NpParam = NpAdapter.InsertCommand.Parameters.Add("@key",
NpgsqlTypes.NpgsqlDbType.Text);
NpParam.SourceColumn = "key";
NpParam.SourceVersion = DataRowVersion.Current;
NpParam = NpAdapter.InsertCommand.Parameters.Add("@ndata",
NpgsqlTypes.NpgsqlDbType.Bigint);
NpParam.SourceVersion = DataRowVersion.Current;
NpParam.SourceColumn = "ndata";
}
npgsql Connect To Postgresql
.Net
data
Postgresql
Postgresql
1.
connector
NpgsqlConnection myconn = new NpgsqlConnection(Server=localhost;Port=5432;User
Id=username;Password=password;Database=myGisDB;)
-NpgsqlCommand mycommand = new NpgsqlCommand();
-mycommand.Connection = myconn;
2.
Add GeometryColum
Npgsql
ODBC
spatial
-mycommand.CommandText = SELECT
AddGeometryColumn(,myTable,the_geom,4326,GEOMETRY,2);;
-mycommand.ExecuteNonQuery();
3. insert
Attribute Geometry Data
Add
myconn.Open();
mycommand.CommandText = INSERT INTO \myTable\ (\the_geom\) VALUES
(st_setsrid(GeomFromText(:the_geom),:srid));;
mycommand.Parameters.Add(:the_geom, NpgsqlTypes.NpgsqlDbType.string);
mycommand.Parameters[:the_geom].Value = LINESTRING(100.0 14.0,100.0
15.0, 101.0 15.0);
mycommand.Parameters.Add(:srid, NpgsqlTypes.NpgsqlDbType.Integer);
mycommand.Parameters[:srid].Value = 4326; //
mycommand.ExecuteNonQuery();
4.
myconn.Close();
shapfile
NpgsqlTypes.NpgsqlDbType.Bytea
Type
Geometry
Binary
feature shapefile
shapelib
OGR
Npgsql
postgres
1.
namespace Postgres {
2.
3.
using namespace System;
4.
using namespace System::ComponentModel;
5.
using namespace System::Collections;
6.
using namespace System::Windows::Forms;
7.
using namespace System::Data;
8.
using namespace System::Drawing;
9.
using namespace Npgsql;
10.
11.
public ref class Form1 : public System::Windows::Forms::Form
12.
13.
private:
14.
Npgsql::NpgsqlConnection^ conn;
// postgres database connector
15.
16.
public:
17.
Form1(void)
18.
19.
20.
InitializeComponent();
conn = gcnew NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=you
rPassword;Database=mydb;");
21.
22.
23.
protected:
24.
~Form1()
25.
26.
if (components){
27.
delete components;
28.
29.
}
}
30.
31.
32.
public: void Createtables()
{
33.
conn->Open();
34.
String^ query = "DROP TABLE IF EXISTS weather; "
35.
+ "CREATE TABLE weather ("
36.
+ "city
37.
+ "temp_lo
int, "
38.
+ "temp_hi
int, "
39.
+ "prcp
real, "
40.
+ "date
date); "
varchar(80), "
41.
42.
+ "DROP TABLE IF EXISTS cities;"
43.
+ "CREATE TABLE cities ("
44.
+ "name
varchar(80), "
45.
+ "location
point); ";
46.
47.
Npgsql::NpgsqlCommand ^ command = gcnew NpgsqlCommand(query, conn);
48.
Int32 rowsaffected;
49.
try{
50.
rowsaffected = command->ExecuteNonQuery();
51.
this->richTextBox1->AppendText("RESULT CreateTrables():\nsuccessfully created tables\n\n");
52.
53.
finally{
54.
conn->Close();
55.
56.
}
}
57.
58.
public: void InsertData()
59.
60.
conn->Open();
61.
String^ query = "INSERT INTO cities VALUES ('Hobart', '(-120.0, 533.0)'); "
62.
+ "INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)'); "
63.
+ "INSERT INTO weather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27'); "
64.
+ "INSERT INTO weather (city, temp_lo, temp_hi, prcp, date) VALUES ('San Francisco', 43, 57, 0.0
, '1994-11-29'); "
65.
+ "INSERT INTO weather (date, city, temp_hi, temp_lo) VALUES ('1994-11-29', 'Hayward', 54, 37)
; ";
66.
Npgsql::NpgsqlCommand ^ command = gcnew NpgsqlCommand(query, conn);
67.
Int32 rowsaffected;
68.
try{
69.
70.
rowsaffected = command->ExecuteNonQuery();
this->richTextBox1->AppendText("RESULT InsertData():\nadded " + rowsaffected + " lines to tabl
es\n\n");
71.
72.
finally{
73.
conn->Close();
74.
75.
}
}
76.
77.
78.
public: void QuerySingleData()
79.
80.
conn->Open();
81.
String ^ query = "select version()";
82.
Npgsql::NpgsqlCommand ^ command = gcnew NpgsqlCommand(query, conn);
83.
String ^ serverVersion;
84.
try{
85.
serverVersion = (String^)command->ExecuteScalar();
86.
this->richTextBox1->AppendText("RESULT QuerySingleData():\n" + serverVersion + "\n\n");
87.
88.
finally{
89.
conn->Close();
90.
91.
}
}
92.
93.
94.
public: void SelectData()
95.
96.
conn->Open();
97.
String ^ query = "select city, temp_lo, date from weather";
98.
Npgsql::NpgsqlCommand ^ command = gcnew NpgsqlCommand(query, conn);
99.
this->richTextBox1->AppendText("RESULT SelectData():\n");
100.
try{
101.
NpgsqlDataReader ^ dr = command->ExecuteReader();
102.
while(dr->Read()){
103.
richTextBox1->AppendText((String^)dr[0] + "\t");
104.
richTextBox1->AppendText(Convert::ToString(dr[1]) + "\t");
105.
richTextBox1->AppendText(((DateTime^)dr[2])->ToString("dd MMM yyyy") + "\n");
106.
107.
richTextBox1->AppendText("\n");
108.
109.
finally{
110.
conn->Close();
111.
112.
}
}
113.
114.
// Parameters let you dynamically insert values into SQL queries at run-time.
115.
public: void DynamicInsert()
116.
117.
conn->Open();
118.
String ^ query = "select temp_lo, temp_hi from weather where temp_lo = :value1";
119.
// declare parameter in query string
120.
Npgsql::NpgsqlCommand ^ command = gcnew NpgsqlCommand(query, conn);
121.
// add parameter to the parameter collection of the command specifying its type
122.
command->Parameters->Add(gcnew NpgsqlParameter("value1", NpgsqlTypes::NpgsqlDbTy
pe::Integer));
123.
// add a value to it
124.
command->Parameters[0]->Value = 37;
125.
// execute the command as usual
// must exist in the database
126.
try{
127.
NpgsqlDataReader ^ dr = command->ExecuteReader();
128.
richTextBox1->AppendText("RESULT DynamicInsert():\n");
129.
while(dr->Read()){
130.
for(int i = 0; i< dr->FieldCount; i++){
131.
richTextBox1->AppendText(Convert::ToString(dr[i]));
132.
richTextBox1->AppendText("\t");
133.
134.
richTextBox1->AppendText("\n");
135.
136.
137.
finally{
138.
conn->Close();
139.
140.
141.
142.
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
143.
try{
144.
Createtables();
// uses Parameters
145.
InsertData();
146.
QuerySingleData();
147.
SelectData();
148.
DynamicInsert();
149.
150.
catch(Exception ^e){
151.
Warning);
MessageBox::Show(e->Message, "Warning", MessageBoxButtons::OK, MessageBoxIcon::
152.
153.
154.
};
155.