Python資料庫操作 pyodbc

2021-10-05 18:20:44 字數 2376 閱讀 7368

使用pip或者pipnv方式安裝均可。

pip install pyodbc
pipenv install pyodbc
訪問access資料庫,需要手動安裝access資料庫引擎。需要注意,access資料庫引擎版本和位數需要和office對應,否則會安裝失敗。以下**均在office2016(64bit)和access2016(64bit)資料庫引擎平台下驗證。access資料庫引擎可在官網找到相應的鏈結。

安裝完成後,可以在windwos管理工具->odbc資料來源管理程式檢視到access資料庫的平台及驅動資訊。

建立資料庫需要使用access桌面軟體,建立test.accdb檔案作為測試資料庫。(右鍵新建*.accdb檔案也可以。)

注意:建立後不要使用access開啟,否則部分操作回應access占用而操作失敗

# 連線

datafile = "g:/workspace/python/test.accdb" # 貌似要用絕對路徑

database = 'driver=;dbq=' + datafile

connect = pyodbc.connect(database) # 連線資料庫

cursor = connect.cursor() # 獲取cursor游標

# 建立表

cursor.execute("create table user (id int primary key, name varchar(255), tele varchar(14), addr varchar(255))")

# 新增資料

cursor.execute(

"insert into user values(1, 'a', '0-12345678', '0-abcdefg')"

)cursor.execute(

"insert into user values(2, 'b', '1-12345678', '1-abcdefg')"

)cursor.execute(

"insert into user values(3, 'c', '2-12345678', '2-abcdefg')"

)cursor.execute(

"insert into user values(4, 'd', '3-12345678', '3-abcdefg')"

)cursor.commit(

)

# 遍歷資料庫:輸出表的資訊

print

("database table list info: "

)for table_info in cursor.tables(tabletype=

'table'):

print

(table_info.table_name)

# 遍歷表資料:輸出各行的資訊

print

("database table data info: "

)cursor.execute(

"select * from user"

)datas = cursor.fetchall(

)for data in datas:

print

(data)

# 遍歷表資訊:輸出指定字段行資料

print

("database table data info: "

)cursor.execute(

"select * from user where name='a'"

)print

(cursor.fetchall(

))

# 修改指定資料

cursor.execute(

"update user set tele ='1-87654321' where name='a'"

)

cursor.execute(

"delete from user where name='d'"

)

cursor.execute(

"drop table user"

)

cursor.commit(

)# 提交資料

cursor.close(

)# 關閉游標

connect.close(

)# 斷開連線

python mysql資料庫連線 pyodbc

import pyodbc cnxn pyodbc.connect driver server database uid pwd cursor cnxn.cursor cursor.execute select id from datatable row cursor.fetchone 其中 其中 ...

python 資料庫操作

例子1 建立乙個資料庫 coding utf 8 中文注釋 import mysqldb 建立和資料庫系統的連線 conn mysqldb.connect host localhost user root passwd 獲取操作游標 cursor conn.cursor 執行sql,建立乙個資料庫 ...

Python資料庫操作

我們之前接觸過的儲存資料的方式都是 1.字串 2.列表 3.元組 4.字典 以上方式其實是屬於同一種方式,即將資料儲存在記憶體中 實際在開發過程中,資料儲存主要有三種形式 1.將資料儲存到記憶體中 優點 使用方便,讀寫速度快 缺點 程式關閉的時候,記憶體會釋放,資料會消失 2.將資料寫入到檔案中 優...