Python使用ACCESS
时间: 2023-11-19 17:10:38 浏览: 79
AccessControl-4.1-cp27-cp27m-win_amd64.whl.zip
Python可以通过pyodbc库或者pypyodbc库来使用ACCESS数据库。
1. 安装pyodbc或pypyodbc库
```
pip install pyodbc
```
或
```
pip install pypyodbc
```
2. 连接ACCESS数据库
```python
import pyodbc
# 驱动
driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
# 数据库路径
db_path = 'C:/Users/Username/Documents/AccessDatabase.accdb'
# 连接数据库
cnxn = pyodbc.connect('DRIVER=' + driver + ';DBQ=' + db_path)
# 获取游标
cursor = cnxn.cursor()
```
```python
import pypyodbc
# 数据库路径
db_path = 'C:/Users/Username/Documents/AccessDatabase.accdb'
# 连接数据库
cnxn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + db_path)
# 获取游标
cursor = cnxn.cursor()
```
3. 查询数据
```python
# 查询语句
sql = 'SELECT * FROM table'
# 执行查询
cursor.execute(sql)
# 获取查询结果
result = cursor.fetchall()
# 遍历结果
for row in result:
print(row)
```
4. 插入数据
```python
# 插入语句
sql = "INSERT INTO table (column1, column2) VALUES (?, ?)"
# 插入数据
cursor.execute(sql, ('value1', 'value2'))
# 提交事务
cnxn.commit()
```
5. 更新数据
```python
# 更新语句
sql = "UPDATE table SET column1 = ? WHERE column2 = ?"
# 更新数据
cursor.execute(sql, ('new_value', 'condition_value'))
# 提交事务
cnxn.commit()
```
6. 删除数据
```python
# 删除语句
sql = "DELETE FROM table WHERE column1 = ?"
# 删除数据
cursor.execute(sql, ('value_to_delete',))
# 提交事务
cnxn.commit()
```
7. 关闭游标和连接
```python
cursor.close()
cnxn.close()
```
阅读全文