搜尋
首頁資料庫mysql教程Access PostgreSQL with Python

http://wiki.postgresql.org/wiki/Psycopg2_Tutorial There are any number of programming languages available for you to use with PostgreSQL. One could argue that PostgreSQL as an Open Source database has one of the largest libraries of Applic

http://wiki.postgresql.org/wiki/Psycopg2_Tutorial

There are any number of programming languages available for you to use with PostgreSQL. One could argue that PostgreSQL as an Open Source database has one of the largest libraries of Application Programmable Interfaces (API) available for various languages.

One such language is Python and it happens to be one of my favored languages. I use it for almost all hacking that I do. Why? Well to be honest it is because I am not that great of a programmer. I am a database administrator and operating system consultant by trade. Python ensures that the code that I write is readable by other more talented programmers 6 months from when I stopped working on it.

Nine times out of ten, when I am using Python, I am using the language to communicate with a PostgreSQL database. My driver of choice when doing so is called Psycopg. Recently Psycopg2 has been under heavy development and is currently in Beta 4. It is said that this will be the last Beta. Like the first release of Pyscopg the driver is designed to be lightweight, fast.

The following article discusses how to connect to PostgreSQL with Psycopg2 and also illustrates some of the nice features that come with the driver. The test platform for this article is Psycopg2, Python 2.4, and PostgreSQL 8.1dev.

Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-threaded applications and manages its own connection pool. Other interesting features of the adapter are that if you are using the PostgreSQL array data type, Psycopg will automatically convert a result using that data type to a Python list.

The following discusses specific use of Psycopg. It does not try to implement a lot of Object Orientated goodness but to provide clear and concise syntactical examples of uses the driver with PostgreSQL. Making the initial connection:

#!/usr/bin/python2.4
#
# Small script to show PostgreSQL and Pyscopg together
#

import psycopg2

try:
    conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'")
except:
    print "I am unable to connect to the database"

The above will import the adapter and try to connect to the database. If the connection fails a print statement will occur to STDOUT. You could also use the exception to try the connection again with different parameters if you like.

The next step is to define a cursor to work with. It is important to note that Python/Psycopg cursors are not cursors as defined by PostgreSQL. They are completely different beasts.

cur = conn.cursor()

Now that we have the cursor defined we can execute a query.

cur.execute("""SELECT datname from pg_database""")

When you have executed your query you need to have a list [variable?] to put your results in.

rows = cur.fetchall()

Now all the results from our query are within the variable named rows. Using this variable you can start processing the results. To print the screen you could do the following.

print "\nShow me the databases:\n"
for row in rows:
    print "   ", row[0]

Everything we just covered should work with any database that Python can access. Now let's review some of the finer points available. PostgreSQL does not have an autocommit facility which means that all queries will execute within a transaction.

Execution within a transaction is a very good thing, it ensures data integrity and allows for appropriate error handling. However there are queries that can not be run from within a transaction. Take the following example.

#/usr/bin/python2.4
#
#

import psycopg2

# Try to connect

try:
    conn=psycopg2.connect("dbname='template1' user='dbuser' password='mypass'")
except:
    print "I am unable to connect to the database."
    
cur = conn.cursor()
try:
    cur.execute("""DROP DATABASE foo_test""")
except:
    print "I can't drop our test database!"

This code would actually fail with the printed message of "I can't drop our test database!" PostgreSQL can not drop databases within a transaction, it is an all or nothing command. If you want to drop the database you would need to change the isolation level of the database this is done using the following.

conn.set_isolation_level(0)

You would place the above immediately preceding the DROP DATABASE cursor execution.

The psycopg2 adapter also has the ability to deal with some of the special data types that PostgreSQL has available. One such example is arrays. Let's review the table below:

      Table "public.bar"
 Column |  Type  |                      Modifiers
--------+--------+-----------------------------------------------------
 id     | bigint | not null default nextval('public.bar_id_seq'::text)
 notes  | text[] |
Indexes:
    "bar_pkey" PRIMARY KEY, btree (id)

The notes column in the bar table is of type text[]. The [] has special meaning in PostgreSQL. The [] represents that the type is not just text but an array of text. To insert values into this table you would use a statement like the following.

foo=# insert into bar(notes) values ('{An array of text, Another array of text}');

Which when selected from the table would have the following representation.

foo=# select * from bar;
 id |                    notes
----+----------------------------------------------
  2 | {"An array of text","Another array of text"}
(1 row)

Some languages and database drivers would insist that you manually create a routine to parse the above array output. Psycopg2 does not force you to do that. Instead it converts the array into a Python list.

#/usr/bin/python2.4
#
#

import psycopg2

# Try to connect

try:
    conn=psycopg2.connect("dbname='foo' user='dbuser' password='mypass'")
except:
    print "I am unable to connect to the database."

cur = conn.cursor()
try:
    cur.execute("""SELECT * from bar""")
except:
    print "I can't SELECT from bar"

rows = cur.fetchall()
print "\nRows: \n"
for row in rows:
    print "   ", row[1]

When the script was executed the following output would be presented.

[jd@jd ~]$ python test.py

Rows:

    ['An array of text', 'Another array of text']

You could then access the list in Python with something similar to the following.

#/usr/bin/python2.4
#
#

import psycopg2

# Try to connect

try:
    conn=psycopg2.connect("dbname='foo' user='dbuser' password='mypass'")
except:
    print "I am unable to connect to the database."

cur = conn.cursor()
try:
    cur.execute("""SELECT * from bar""")
except:
    print "I can't SELECT from bar"

rows = cur.fetchall()
for row in rows:
    print "   ", row[1][1]

The above would output the following.

Rows:

    Another array of text

Some programmers would prefer to not use the numeric representation of the column. For example row[1][1], instead it can be easier to use a dictionary. Using the example with slight modification.

#/usr/bin/python2.4
#
#

# load the adapter
import psycopg2

# load the psycopg extras module
import psycopg2.extras

# Try to connect

try:
    conn=psycopg2.connect("dbname='foo' user='dbuser' password='mypass'")
except:
    print "I am unable to connect to the database."

# If we are accessing the rows via column name instead of position we 
# need to add the arguments to conn.cursor.

cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
try:
    cur.execute("""SELECT * from bar""")
except:
    print "I can't SELECT from bar"

#
# Note that below we are accessing the row via the column name.

rows = cur.fetchall()
for row in rows:
    print "   ", row['notes'][1]

The above would output the following.

Rows:

    Another array of text

Notice that we did not use row[1] but instead used row['notes'] which signifies the notes column within the bar table.

A last item I would like to show you is how to insert multiple rows using a dictionary. If you had the following:

namedict = ({"first_name":"Joshua", "last_name":"Drake"},
            {"first_name":"Steven", "last_name":"Foo"},
            {"first_name":"David", "last_name":"Bar"})

You could easily insert all three rows within the dictionary by using:

cur = conn.cursor()
cur.executemany("""INSERT INTO bar(first_name,last_name) VALUES (%(first_name)s, %(last_name)s)""", namedict)

The cur.executemany statement will automatically iterate through the dictionary and execute the INSERT query for each row.

The only downside that I run into with Pyscopg2 and PostgreSQL is it is a little behind in terms of server side support functions like server side prepared queries but it is said that the author is expecting to implement these features in the near future.


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
MySQL與Sqlite有何不同?MySQL與Sqlite有何不同?Apr 24, 2025 am 12:12 AM

MySQL和SQLite的主要區別在於設計理念和使用場景:1.MySQL適用於大型應用和企業級解決方案,支持高性能和高並發;2.SQLite適合移動應用和桌面軟件,輕量級且易於嵌入。

MySQL中的索引是什麼?它們如何提高性能?MySQL中的索引是什麼?它們如何提高性能?Apr 24, 2025 am 12:09 AM

MySQL中的索引是數據庫表中一列或多列的有序結構,用於加速數據檢索。 1)索引通過減少掃描數據量提升查詢速度。 2)B-Tree索引利用平衡樹結構,適合範圍查詢和排序。 3)創建索引使用CREATEINDEX語句,如CREATEINDEXidx_customer_idONorders(customer_id)。 4)複合索引可優化多列查詢,如CREATEINDEXidx_customer_orderONorders(customer_id,order_date)。 5)使用EXPLAIN分析查詢計劃,避

說明如何使用MySQL中的交易來確保數據一致性。說明如何使用MySQL中的交易來確保數據一致性。Apr 24, 2025 am 12:09 AM

在MySQL中使用事務可以確保數據一致性。 1)通過STARTTRANSACTION開始事務,執行SQL操作後用COMMIT提交或ROLLBACK回滾。 2)使用SAVEPOINT可以設置保存點,允許部分回滾。 3)性能優化建議包括縮短事務時間、避免大規模查詢和合理使用隔離級別。

在哪些情況下,您可以選擇PostgreSQL而不是MySQL?在哪些情況下,您可以選擇PostgreSQL而不是MySQL?Apr 24, 2025 am 12:07 AM

選擇PostgreSQL而非MySQL的場景包括:1)需要復雜查詢和高級SQL功能,2)要求嚴格的數據完整性和ACID遵從性,3)需要高級空間功能,4)處理大數據集時需要高性能。 PostgreSQL在這些方面表現出色,適合需要復雜數據處理和高數據完整性的項目。

如何保護MySQL數據庫?如何保護MySQL數據庫?Apr 24, 2025 am 12:04 AM

MySQL數據庫的安全可以通過以下措施實現:1.用戶權限管理:通過CREATEUSER和GRANT命令嚴格控制訪問權限。 2.加密傳輸:配置SSL/TLS確保數據傳輸安全。 3.數據庫備份和恢復:使用mysqldump或mysqlpump定期備份數據。 4.高級安全策略:使用防火牆限制訪問,並啟用審計日誌記錄操作。 5.性能優化與最佳實踐:通過索引和查詢優化以及定期維護兼顧安全和性能。

您可以使用哪些工具來監視MySQL性能?您可以使用哪些工具來監視MySQL性能?Apr 23, 2025 am 12:21 AM

如何有效監控MySQL性能?使用mysqladmin、SHOWGLOBALSTATUS、PerconaMonitoringandManagement(PMM)和MySQLEnterpriseMonitor等工具。 1.使用mysqladmin查看連接數。 2.用SHOWGLOBALSTATUS查看查詢數。 3.PMM提供詳細性能數據和圖形化界面。 4.MySQLEnterpriseMonitor提供豐富的監控功能和報警機制。

MySQL與SQL Server有何不同?MySQL與SQL Server有何不同?Apr 23, 2025 am 12:20 AM

MySQL和SQLServer的区别在于:1)MySQL是开源的,适用于Web和嵌入式系统,2)SQLServer是微软的商业产品,适用于企业级应用。两者在存储引擎、性能优化和应用场景上有显著差异,选择时需考虑项目规模和未来扩展性。

在哪些情況下,您可以選擇SQL Server而不是MySQL?在哪些情況下,您可以選擇SQL Server而不是MySQL?Apr 23, 2025 am 12:20 AM

在需要高可用性、高級安全性和良好集成性的企業級應用場景下,應選擇SQLServer而不是MySQL。 1)SQLServer提供企業級功能,如高可用性和高級安全性。 2)它與微軟生態系統如VisualStudio和PowerBI緊密集成。 3)SQLServer在性能優化方面表現出色,支持內存優化表和列存儲索引。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能