VC# Connect Postgres
VC# Connect Postgres
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
Insert
+ "'";
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
');
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
Querying everything
Querying
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.
.Net
data
Postgresql
Postgresql
1.
connector
2.
Add GeometryColum
Npgsql
ODBC
spatial
-mycommand.CommandText = SELECT
AddGeometryColumn(,myTable,the_geom,4326,GEOMETRY,2);;
-mycommand.ExecuteNonQuery();
3. insert
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.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
private:
14.
Npgsql::NpgsqlConnection^ conn;
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.
33.
conn->Open();
34.
35.
36.
+ "city
37.
+ "temp_lo
int, "
38.
+ "temp_hi
int, "
39.
+ "prcp
real, "
40.
+ "date
date); "
varchar(80), "
41.
42.
43.
44.
+ "name
varchar(80), "
45.
+ "location
point); ";
46.
47.
48.
Int32 rowsaffected;
49.
try{
50.
rowsaffected = command->ExecuteNonQuery();
51.
52.
53.
finally{
54.
conn->Close();
55.
56.
}
}
57.
58.
59.
60.
conn->Open();
61.
String^ query = "INSERT INTO cities VALUES ('Hobart', '(-120.0, 533.0)'); "
62.
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.
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.
79.
80.
conn->Open();
81.
82.
83.
String ^ serverVersion;
84.
try{
85.
serverVersion = (String^)command->ExecuteScalar();
86.
87.
88.
finally{
89.
conn->Close();
90.
91.
}
}
92.
93.
94.
95.
96.
conn->Open();
97.
98.
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.
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.
116.
117.
conn->Open();
118.
String ^ query = "select temp_lo, temp_hi from weather where temp_lo = :value1";
119.
120.
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.
126.
try{
127.
NpgsqlDataReader ^ dr = command->ExecuteReader();
128.
richTextBox1->AppendText("RESULT DynamicInsert():\n");
129.
while(dr->Read()){
130.
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.
143.
try{
144.
Createtables();
// uses Parameters
145.
InsertData();
146.
QuerySingleData();
147.
SelectData();
148.
DynamicInsert();
149.
150.
catch(Exception ^e){
151.
Warning);
152.
153.
154.
};
155.