学习Python的过程中,我们会遇到Access的读写问题,这时我们可以利用win32.client模块的COM组件访问功能,通过ADODB操作Access的文件。
需要下载安装pywin32与AccessDatabaseEngine.exe
pywin32下载地址:https://www.jb51.net/softs/695840.html
AccessDatabaseEngine.exe下载 https://www.jb51.net/softs/291508.html
64位下载:https://www.jb51.net/softs/291504.html
1、导入模块
import win32com.client
2、建立数据库连接
conn = win32com.client.Dispatch(r"ADODB.Connection") DSN = 'PROVIDER = Microsoft.Jet.OLEDB.4.0;DATA SOURCE = test.mdb' conn.Open(DSN)
3、打开一个记录集
rs = win32com.client.Dispatch(r'ADODB.Recordset') rs_name = 'MEETING_PAPER_INFO' rs.Open('[' + rs_name + ']', conn, 1, 3)
4、对记录集操作
rs.AddNew() #添加一条新记录 rs.Fields.Item(0).Value = "data" #新记录的第一个记录为"data" rs.Update() #更新
5、用SQL语句来增、删、改数据
# 增 sql = "Insert Into [rs_name] (id, innerserial, mid) Values ('002133800088980002', 2, '21338')" #sql语句 conn.Execute(sql) #执行sql语句 # 删 sql = "Delete * FROM " + rs_name + " where innerserial = 2" conn.Execute(sql) # 改 sql = "Update " + rs_name + " Set mid = 2016 where innerserial = 3" conn.Execute(sql)
6、遍历记录
rs.MoveFirst() #光标移到首条记录 count = 0 while True: if rs.EOF: break else: for i in range(rs.Fields.Count): #字段名:字段内容 print(rs.Fields[i].Name, ":", rs.Fields[i].Value) count += 1 rs.MoveNext()
7、关闭数据库
conn.close()
补充
如果是python3好像需要用到pypyodbc
# 话不多说,码上见分晓!
使用模块: pypyodbc
例子和安装详见:
https://github.com/jiangwen365/pypyodbc/
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "loki" import time import pypyodbc as mdb # 连接mdb文件 connStr = (r'Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\MDB_demo\demo.mdb;' r'Database=bill;' ) conn = mdb.win_connect_mdb(connStr) # connStr = ( # r'Driver={SQL Sever};' # r'Server=sqlserver;' # r'Database=bill;' # r'UID=sa;' # r'PWD=passwd' # ) # # conn = mdb.connect(connStr) # 创建游标 cur = conn.cursor() cur.execute('SELECT * FROM bill;') for col in cur.description: # 展示行描述 print(col[0], col[1]) result = cur.fetchall() for row in result: # 展示个字段的值 print(row) print(row[1], row[2]
官方给的例子mdb
# Microsoft Access DB import pypyodbc connection = pypyodbc.win_create_mdb('D:\\database.mdb') SQL = 'CREATE TABLE saleout (id COUNTER PRIMARY KEY,product_name VARCHAR(25));' connection.cursor().execute(SQL) connection.close()
#SQL Server 2000/2005/2008 (and probably 2012 and 2014)
#SQL Server 2000/2005/2008 (and probably 2012 and 2014) import pypyodbc as pyodbc # you could alias it to existing pyodbc code (not every code is compatible) db_host = 'serverhost' db_name = 'database' db_user = 'username' db_password = 'password' connection_string = 'Driver={SQL Server};Server=' + db_host + ';Database=' + db_name + ';UID=' + db_user + ';PWD=' + db_password + ';' db = pyodbc.connect(connection_string) SQL = 'CREATE TABLE saleout (id COUNTER PRIMARY KEY,product_name VARCHAR(25));' db.cursor().execute(SQL) # Doing a simple SELECT query connStr = ( r'Driver={SQL Server};' r'Server=sqlserver;' #r'Server=127.0.0.1,52865;' + #r'Server=(local)\SQLEXPRESS;' r'Database=adventureworks;' #r'Trusted_Connection=Yes;' r'UID=sa;' r'PWD=sapassword;' ) db = pypyodbc.connect(connStr) cursor = db.cursor() # Sample with just a raw query: cursor.execute("select client_name, client_lastname, [phone number] from Clients where client_id like '01-01-00%'") # Using parameters (IMPORTANT: YOU SHOULD USE TUPLE TO PASS PARAMETERS) # Python note: a tuple with just one element must have a trailing comma, otherwise is just a enclosed variable cursor.execute("select client_name, client_lastname, [phone number] " "from Clients where client_id like ", ('01-01-00%', )) # Sample, passing more than one parameter cursor.execute("select client_name, client_lastname, [phone number] " "from Clients where client_id like ", ('01-01-00%', 28)) # Method 1, simple reading using cursor while True: row = cursor.fetchone() if not row: break print("Client Full Name (phone number): ", row['client_name'] + ' ' + row['client_lastname'] + '(' + row['phone number'] + ')') # Method 2, we obtain dict's all records are loaded at the same time in memory (easy and verbose, but just use it with a few records or your app will consume a lot of memory), was tested in a modern computer with about 1000 - 3000 records just fine... import pprint; pp = pprint.PrettyPrinter(indent=4) columns = [column[0] for column in cursor.description] for row in cursor.fetchall(): pp.pprint(dict(zip(columns, row))) # Method 3, we obtain a list of dict's (represents the entire query) query_results = [dict(zip([column[0] for column in cursor.description], row)) for row in cursor.fetchall()] pp.pprint(query_results) # When cursor was used must be closed, if you will not use again the db connection must be closed too. cursor.close() db.close()
How to use it without install (the latest version from here)
Just copy the latest pypyodbc.py downloaded from this repository on your project folder and import the module.
Install
If you have pip available (keep in mind that the version on pypi may be old):
pip install pypyodbc
Or get the latest pypyodbc.py script from GitHub (Main Development site)
python setup.py install
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新动态
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]