使用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 相关文章推荐
wxpython学习笔记(推荐查看)
Jun 09 Python
Python实现多行注释的另类方法
Aug 22 Python
利用 Monkey 命令操作屏幕快速滑动
Dec 07 Python
python Pygame的具体使用讲解
Nov 03 Python
python机器学习之决策树分类详解
Dec 20 Python
Python+PyQT5的子线程更新UI界面的实例
Jun 14 Python
Python 单例设计模式用法实例分析
Sep 23 Python
Python 获取命令行参数内容及参数个数的实例
Dec 20 Python
Python基于pyecharts实现关联图绘制
Mar 27 Python
Python如何使用27行代码绘制星星图
Jul 20 Python
重构Python代码的六个实例
Nov 25 Python
python创建字典及相关管理操作
Apr 13 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
ie6 动态缩略图不显示的原因
2009/06/21 PHP
PHP获取表单textarea数据中的换行问题
2010/09/10 PHP
php数组函数序列之krsort()- 对数组的元素键名进行降序排序,保持索引关系
2011/11/02 PHP
php异常处理使用示例
2014/02/25 PHP
PHP按行读取文件时删除换行符的3种方法
2014/05/04 PHP
PHP 导出Excel示例分享
2014/08/18 PHP
PHP实现设计模式中的抽象工厂模式详解
2014/10/11 PHP
php调用淘宝开放API实现根据卖家昵称获取卖家店铺ID的方法
2015/07/29 PHP
详解WordPress开发中get_header()获取头部函数的用法
2016/01/08 PHP
PHP架构及原理知识点详解
2019/12/22 PHP
用javascript实现给图片加链接
2007/08/15 Javascript
JavaScript 字符串乘法
2009/08/20 Javascript
javascript KeyDown、KeyPress和KeyUp事件的区别与联系
2009/12/03 Javascript
全面兼容的javascript时间格式化函数(比较实用)
2014/05/14 Javascript
node.js中的fs.fchmodSync方法使用说明
2014/12/16 Javascript
javascript判断变量是否有值的方法
2015/04/20 Javascript
购物车前端开发(jQuery和bootstrap3)
2016/08/27 Javascript
关于javascript原型的修改与重写(覆盖)差别详解
2016/08/31 Javascript
Angular路由简单学习
2016/12/26 Javascript
微信小程序中的onLoad详解及简单实例
2017/04/05 Javascript
Vue仿今日头条实例详解
2018/02/06 Javascript
详解vue2.0+vue-video-player实现hls播放全过程
2018/03/02 Javascript
详解vue-cli项目中怎么使用mock数据
2018/05/29 Javascript
WebPack工具运行原理及入门教程
2020/12/02 Javascript
Java实现的执行python脚本工具类示例【使用jython.jar】
2018/03/29 Python
Linux CentOS Python开发环境搭建教程
2018/11/28 Python
对python数据切割归并算法的实例讲解
2018/12/12 Python
python爬虫之验证码篇3-滑动验证码识别技术
2019/04/11 Python
python实现LBP方法提取图像纹理特征实现分类的步骤
2019/07/11 Python
基于python实现音乐播放器代码实例
2020/07/01 Python
Python中openpyxl实现vlookup函数的实例
2020/10/28 Python
Python就将所有的英文单词首字母变成大写
2021/02/12 Python
幼儿园教师工作制度
2014/01/22 职场文书
请假条范文大全
2014/04/10 职场文书
民族团结先进集体事迹材料
2014/05/22 职场文书
奖励通知
2015/04/22 职场文书