Skip to content

파이썬 라이브러리 pyodbc #

Find similar titles

3회 업데이트 됨.

Edit

Structured data

Category
Programming

ODBC 드라이버를 통해 데이터베이스와 연결할 수 있는 파이썬 라이브러리 pyodbc #

ODBC 를 통해 데이터베이스와 연결할 수 있도록 해주는 파이썬 라이브러리로 예전에는 구글에서 관리되었으나 현재는 GitHub을 통해 관리되고 있다.

공식홈페이지

설치 #

pip install pyodbc

사용법 #

pyodbc를 사용하여 DB에 접속하기 위해서는 해당 데이터베이스가 ODBC를 지원해야하며 ODBC 드라이버가 설치되어 있어야 한다.

DB 연결하기 #

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()


cnxn = pyodbc.connect('DSN=test;PWD=password')
cursor = cnxn.cursor()

Select #

cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
if row:
    print(row)

cursor.execute("select user_id, user_name from users")
rows = cursor.fetchall()
for row in rows:
    print(row.user_id, row.user_name)

파라미터 넘기기 #

cursor.execute(
    """
    select user_id, user_name
      from users
     where last_logon < ?
           and bill_overdue = ?
    """, '2001-01-01', 1)

cursor.execute(
    """
    select user_id, user_name
      from users
     where last_logon < ?
           and bill_overdue = ?
    """, ['2001-01-01', 1])

Insert #

cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()

cursor.execute("insert into products(id, name) values (?, ?)", 'pyodbc', 'awesome library')
cnxn.commit()

커밋(cnxn.commit)을 수행하지 않으면 변경내용은 손실된다.

update #

cursor.execute("delete from products where id <> ?", 'pyodbc')
print('Deleted {} inferior products'.format(cursor.rowcount))
cnxn.commit()

deleted = cursor.execute("delete from products where id <> 'pyodbc'").rowcount
cnxn.commit()

커밋(cnxn.commit)을 수행하지 않으면 변경내용은 손실된다.

Suggested Pages #

0.0.1_20230725_7_v68