데이터 베이스 MySQL 튜토리얼 Access PostgreSQL with Python

Access PostgreSQL with Python

Jun 07, 2016 pm 03:49 PM
access postgresql python with

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으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. 크로스 플레이가 있습니까?
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

파이썬 : 자동화, 스크립팅 및 작업 관리 파이썬 : 자동화, 스크립팅 및 작업 관리 Apr 16, 2025 am 12:14 AM

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

터미널 VSCODE에서 프로그램을 실행하는 방법 터미널 VSCODE에서 프로그램을 실행하는 방법 Apr 15, 2025 pm 06:42 PM

vs 코드에서는 다음 단계를 통해 터미널에서 프로그램을 실행할 수 있습니다. 코드를 준비하고 통합 터미널을 열어 코드 디렉토리가 터미널 작업 디렉토리와 일치하는지 확인하십시오. 프로그래밍 언어 (예 : Python의 Python Your_file_name.py)에 따라 실행 명령을 선택하여 성공적으로 실행되는지 여부를 확인하고 오류를 해결하십시오. 디버거를 사용하여 디버깅 효율을 향상시킵니다.

VScode 확장자가 악의적입니까? VScode 확장자가 악의적입니까? Apr 15, 2025 pm 07:57 PM

VS 코드 확장은 악의적 인 코드 숨기기, 취약성 악용 및 합법적 인 확장으로 자위하는 등 악성 위험을 초래합니다. 악의적 인 확장을 식별하는 방법에는 게시자 확인, 주석 읽기, 코드 확인 및주의해서 설치가 포함됩니다. 보안 조치에는 보안 인식, 좋은 습관, 정기적 인 업데이트 및 바이러스 백신 소프트웨어도 포함됩니다.

VScode 란 무엇입니까? VScode 란 무엇입니까? Apr 15, 2025 pm 06:45 PM

VS Code는 Full Name Visual Studio Code로, Microsoft가 개발 한 무료 및 오픈 소스 크로스 플랫폼 코드 편집기 및 개발 환경입니다. 광범위한 프로그래밍 언어를 지원하고 구문 강조 표시, 코드 자동 완료, 코드 스 니펫 및 스마트 프롬프트를 제공하여 개발 효율성을 향상시킵니다. 풍부한 확장 생태계를 통해 사용자는 디버거, 코드 서식 도구 및 GIT 통합과 같은 특정 요구 및 언어에 확장을 추가 할 수 있습니다. VS 코드에는 코드에서 버그를 신속하게 찾아서 해결하는 데 도움이되는 직관적 인 디버거도 포함되어 있습니다.

vScode를 Mac에서 사용할 수 있습니다 vScode를 Mac에서 사용할 수 있습니다 Apr 15, 2025 pm 07:45 PM

VS 코드는 MACOS에서 잘 수행되며 개발 효율성을 향상시킬 수 있습니다. 설치 및 구성 단계에는 다음이 포함됩니다. 설치 대 코드 및 구성. 언어 별 확장 (예 : JavaScript 용 Eslint)을 설치하십시오. 과도한 스타트 업이 느려지는 것을 피하려면 확장 기능을주의 깊게 설치하십시오. GIT 통합, 터미널 및 디버거와 같은 기본 기능을 배우십시오. 적절한 테마와 코드 글꼴을 설정하십시오. 참고 잠재적 문제 : 연장 호환성, 파일 권한 등

Python vs. JavaScript : 학습 곡선 및 사용 편의성 Python vs. JavaScript : 학습 곡선 및 사용 편의성 Apr 16, 2025 am 12:12 AM

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

VSCODE에서 진행중인 것은 Python을 실행하지 않습니다 VSCODE에서 진행중인 것은 Python을 실행하지 않습니다 Apr 15, 2025 pm 06:00 PM

가장 일반적인 "Python을 실행할 수 없음"문제는 Python 통역사 경로의 오해에서 비롯됩니다. 솔루션에는 Python 설치 확인, 대 코드 구성 및 가상 환경 사용이 포함됩니다. 또한 가상 환경을 사용한 종속성 분리, 중단 점을 사용한 코드 실행 추적 및 모니터링 표현식 등을 사용하여 실시간의 가변 변경을 추적하는 등 브레이크 포인트 디버깅, 가변 모니터링, 로그 출력 및 코드 형식과 같은 효율적인 디버깅 기술 및 모범 사례가 있습니다.

코드를 실행할 수 있습니다 코드를 실행할 수 있습니다 Apr 15, 2025 pm 08:21 PM

예, 대 코드는 Python 코드를 실행할 수 있습니다. 대 코드에서 Python을 효율적으로 실행하려면 다음 단계를 완료하십시오. Python 통역사를 설치하고 환경 변수를 구성하십시오. 대 코드에 파이썬 확장을 설치하십시오. 명령 줄을 통해 대 코드 터미널에서 파이썬 코드를 실행하십시오. VS Code의 디버깅 기능 및 코드 서식을 사용하여 개발 효율성을 향상시킵니다. 좋은 프로그래밍 습관을 채택하고 성능 분석 도구를 사용하여 코드 성능을 최적화하십시오.

See all articles