侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

使用Python对Access读写操作

Python  /  管理员 发布于 7年前   228

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

需要下载安装pywin32与AccessDatabaseEngine.exe

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

AccessDatabaseEngine.exe下载 https:///softs/291508.html

64位下载:https:///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 = 0while 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 timeimport 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 DBimport 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 queryconnStr = ( 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 variablecursor.execute("select client_name, client_lastname, [phone number] ""from Clients where client_id like ?", ('01-01-00%', ))# Sample, passing more than one parametercursor.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 cursorwhile 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中Django发送带图片和附件的邮件
    下一条:
    使用Python对Excel进行读写操作
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客