เป็นคำถามติดค้างนะครับ เนื่องจากมีพี่ท่านหนึ่งได้ถามเกี่ยวกับการใช้ .Net ต่อเข้าสู่ Postgresql โดยต้องการจะนำเข้าหรืออัพเดตข้อมูล spatial data การทำงานก็ไม่ยากครับสามารถเขียนโปรแกรมผ่านช่องทาง Npgsql ซึ่งสามารถทำการติดตั้งได้จาก Postgresql (รับรองว่าเร็วกว่าผ่าน ODBC ครับ) โดยมีแนวทางง่ายๆดังนี้นะครับ
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
-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();
ทดลองนำไปประยุกต์ใช้ดูนะครับ โดยกรณีที่มี Geometry มากกว่า 1 หรือนำมาจาก shapfile ก็สามารถกำหนด Type เป็น Binary ได้โดยใช้ NpgsqlTypes.NpgsqlDbType.Bytea ส่วนการเข้าถึงข้อมูล feature ในshapefile ก็ใช้ shapelib หรือ OGR ก็ได้ครับ
ปล.อย่าลืมติดตั้ง Npgsql ให้ postgres ก่อนใช้งานนะครับ ติดขัดประการใด email มาถามได้ครับ
.gif)