使用Python对Access读写操作


Posted in Python onMarch 30, 2017

学习Python的过程中,我们会遇到Access的读写问题,这时我们可以利用win32.client模块的COM组件访问功能,通过ADODB操作Access的文件。

需要下载安装pywin32与AccessDatabaseEngine.exe

pywin32下载地址:https://3water.com/softs/695840.html

AccessDatabaseEngine.exe下载 https://3water.com/softs/291508.html

64位下载:https://3water.com/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 ? and client_age < ?", ('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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

Python 相关文章推荐
使用Python的Zato发送AMQP消息的教程
Apr 16 Python
Python运算符重载用法实例分析
Jun 01 Python
Python实现1-9数组形成的结果为100的所有运算式的示例
Nov 03 Python
PyTorch CNN实战之MNIST手写数字识别示例
May 29 Python
Scrapy基于selenium结合爬取淘宝的实例讲解
Jun 13 Python
Django处理多用户类型的方法介绍
May 18 Python
详解Python3 pandas.merge用法
Sep 05 Python
Matplotlib使用字符串代替变量绘制散点图的方法
Feb 17 Python
python如何保存文本文件
Jun 07 Python
Python建造者模式案例运行原理解析
Jun 29 Python
python入门教程之基本算术运算符
Nov 13 Python
Python tkinter之Bind(绑定事件)的使用示例
Feb 05 Python
使用Python对Excel进行读写操作
Mar 30 #Python
浅述python中argsort()函数的实例用法
Mar 30 #Python
Windows下安装python2和python3多版本教程
Mar 30 #Python
详解Python之数据序列化(json、pickle、shelve)
Mar 30 #Python
python类的继承实例详解
Mar 30 #Python
django轻松使用富文本编辑器CKEditor的方法
Mar 30 #Python
python下读取公私钥做加解密实例详解
Mar 29 #Python
You might like
php注入实例
2006/10/09 PHP
PHP和Mysqlweb应用开发核心技术 第1部分 Php基础-3 代码组织和重用2
2011/07/03 PHP
php中根据变量的类型 选择echo或dump
2012/07/05 PHP
php中使用gd库实现下载网页中所有图片
2015/05/12 PHP
PHP生成随机码的思路与方法实例探索
2019/04/11 PHP
Extjs Ext.MessageBox.confirm 确认对话框详解
2010/04/02 Javascript
offsetParent 算法分析
2010/04/05 Javascript
boxy基于jquery的弹出层对话框插件扩展应用 弹出层选择器
2010/11/21 Javascript
php中给js数组赋值方法
2014/03/10 Javascript
基于JQuery实现图片轮播效果(焦点图)
2016/02/02 Javascript
全面解析JavaScript里的循环方法之forEach,for-in,for-of
2020/04/20 Javascript
js 获取今天以及过去日期
2017/04/11 Javascript
JavaScript实现计数器基础方法
2017/10/10 Javascript
JS+HTML5实现获取手机验证码倒计时按钮
2018/08/08 Javascript
浅谈webpack4 图片处理汇总
2018/09/12 Javascript
node实现分片下载的示例代码
2018/10/17 Javascript
JavaScript变量基本使用方法实例分析
2019/11/15 Javascript
vue移动端弹起蒙层滑动禁止底部滑动操作
2020/07/22 Javascript
python操作MySQL数据库的方法分享
2012/05/29 Python
Python使用字典的嵌套功能详解
2019/02/27 Python
Python处理时间日期坐标轴过程详解
2019/06/25 Python
python可视化篇之流式数据监控的实现
2019/08/07 Python
Python 制作查询商品历史价格的小工具
2020/10/20 Python
让IE6、IE7、IE8支持CSS3的脚本
2010/07/20 HTML / CSS
Html5中localStorage存储JSON数据并读取JSON数据的实现方法
2017/02/13 HTML / CSS
canvas 橡皮筋式线条绘图应用方法
2019/02/13 HTML / CSS
财务内勤岗位职责
2014/04/17 职场文书
2014七年级班主任工作总结
2014/12/05 职场文书
2015年小学中秋节活动总结
2015/03/23 职场文书
债务追讨律师函
2015/06/24 职场文书
大学运动会通讯稿
2015/07/18 职场文书
2016党员干部廉政准则学习心得体会
2016/01/20 职场文书
2016年优秀共产党员先进事迹材料
2016/02/29 职场文书
该怎么书写道歉信?
2019/07/03 职场文书
css 边框添加四个角的实现代码
2021/10/16 HTML / CSS
PostgreSQL常用字符串分割函数整理汇总
2022/07/07 PostgreSQL