C#/Python/MATLAB操作PostgreSQL資料庫

天靖居士發表於2017-03-09

PostgreSQL資料庫是一個功能非常強大的開源資料庫,支援多種SQL特性,非常好用。此外由於結合PostGIS可以實現空間資料庫功能,故非常適合GIS領域的使用。本文旨在介紹C#、Python、MATLAB對PostgreSQL進行操作的最基本方法,並實現遠端資料庫的連線。

1.C#連線PostgreSQL

C#連線PostgreSQL需要使用Npgsql,可以通過Visual Studio自帶的nuget下載:

Install-Package Npgsql

之後在程式碼中進行引用即可。

以下是案例程式碼:

 1 //連線資料庫
 2 NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; Port = 5432; UserId = postgres; Password = postgres;Database = db_name");
 3 connection.Open();
 4 
 5 //構造SQL語句
 6 string sqlCommand = "SELECT * FROM table_name";
 7 NpgsqlCommand command = new NpgsqlCommand(sqlCommand, connection);
 8 
 9 //讀取資料
10 NpgsqlDataReader reader = command.ExecuteReader();
11 reader.Read();
12 
13 //獲取資料
14 string data;
15 data=reader.GetString(0);
16 
17 //關閉資料庫
18 connection.Close();

以上即為運算元據庫並讀取資料的方法。首先連線資料庫,之後構造SQL語句並應用於postgresql中,接著構造NpgsqlDataReader,應用NpgsqlCommand.ExecuteReader()方法讀取資料,最終根據讀取出的資料型別進行獲取資料。讀取完畢後不要忘記關閉資料庫。

如果不讀取資料,而僅僅是進行SQL語句的操作,例如修改或刪除等,方法類似,但需要使用NpgsqlCommand.ExecuteNonQuery()方法。

具體程式碼如下:

 1 //連線資料庫
 2 NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; Port = 5432; UserId = postgres; Password = postgres;Database = db_name");
 3 connection.Open();
 4 
 5 //構造SQL語句
 6 string sqlCommand = "UPDATE table_name SET column1=update_attribute WHERE column2=origin_attribute";
 7 NpgsqlCommand command = new NpgsqlCommand(sqlCommand, connection);
 8 
 9 //執行SQL語句
10 command.ExecuteNonQuery();
11 
12 //關閉資料庫
13 connection.Close();

2. Python連線PostgreSQL

使用Python連線PostgreSQL可以使用多種第三方包,而PostgreSQL官方推薦的是Psycopg2這個包,同時支援Python2和Python3的版本。可以使用pip進行安裝:

pip install psycopg2

安裝完成後,即可引用到自己的程式碼中:

import psycopg2

具體連線資料庫並進行操作的程式碼如下:

 1 //連線資料庫
 2 connection = psycopg2.connect(database="db_name", user="postgres",password="postgres",host="127.0.0.1",port="5432")
 3 //獲取遊標
 4 cursor = connection.cursor()
 5 //設定SQL語句
 6 sql_command_select = "SELECT * FROM table_name;"
 7 
 8 try:
 9     //執行SQL語句
10     cursor.execute(sql_command_select)
11     //獲取所有的資料
12     data_all = cursor.fetchall()
13     for data in data_all:
14         //遍歷資料
15         print(data)
16 except Exception as e:
17     print(e)
18     //如果出現錯誤,資料庫復原
19     connection.rollback()
20     

在程式碼中,可以看到首先是連線資料庫,之後獲取遊標,構造SQL語句,並完成了對於資料的查詢。在上例中,獲取全部的資料使用的是cursor.fetchall()函式,倘若只是獲取一條資料,可以使用cursor.fetchone()函式一條一條資料進行讀取。

倘若需要對資料庫進行修改、新增、刪除等功能,只需要使用cursor.execute()函式即可完成SQL語句的執行。

注意對於資料的讀取需要加上異常檢測的程式碼,倘若讀取資料出錯,需要使用connection.rollback()函式恢復到資料庫出錯前的狀態,否則會一直卡在出錯的地方不能繼續。


3. MATLAB連線PostgreSQL

MATLAB連線PostgreSQL資料庫首先需要下載.jar(JDBC)檔案。地址:https://jdbc.postgresql.org/download.html

之後需要將下載的jar檔案新增到MATLAB的jar目錄中。

之後輸入在MATLAB命令列中輸入:

edit classpath.txt

在文字最後新增這條程式碼:

$matlabroot/java/jar/postgresql-9.4.1212.jre6.jar

之後儲存並關閉文字,重啟MATLAB,輸入:

javaclasspath

倘若出現的文字中最後出現了postgresql的路徑,說明新增成功。

之後即可進行資料庫的連線和操作。

MATLAB連線資料庫和運算元據庫的方法如下:

%連線資料庫	
connection=database('db_name','postgres','postgres','org.postgresql.Driver','jdbc:postgresql://localhost:5432/db_name');
%構造SQL語句
sqlcommand='select * from table_name;'
%執行SQL語句
cursor=exec(connection,sqlcommand);
%獲取指定數量的資料
row=fetch(cursor,1);

與前面的程式碼結構類似,首先是連線資料庫,之後構造SQL語句,完成對於資料的查詢。在上例中,獲取資料使用的是fetch()函式,分別傳入連線的資料庫和具體數量。

倘若需要對資料庫進行修改、新增、刪除等功能,只需要使用exec(connection, sqlcommand)函式即可完成SQL語句的執行。

相關文章