Python 数据库
2016-03-20 11:58
489 查看
python内置了SQLite模块并可以方便的连接各种数据库。
python内置sqlite3模块,无需任何配置即可使用。
操作基于事务机制,
更多信息参见Python DOC
这里选用mysqlclient提供MySQL数据库支持,使用
使用本地MySQL Sever提供服务, 因为Python的DB-API是通用的,操作MySQl的代码与SQLite类似。
SQLite
SQLite是一个轻量级数据库一个数据库实例就是一个文件,可以方便的集成到各种应用程序中。python内置sqlite3模块,无需任何配置即可使用。
import sqlite3 # connect db, create if not exists con = sqlite3.connect('test.db') # get the cursor cursor = con.cursor() # excute sql cursor.execute('create table users (user_id varchar(20) primary key, name varchar(20))') cursor.execute('insert into users values ("0", "admin")') print(cursor.rowcount) # print the count of influenced rows # execute query cursor.execute('select * from users where id=?','0') #lag assignment valSet = cursor.fetchall() # get query set print(valSet) # close cursor, commit affair and closeconnection cursor.close() con.commit() # con.close()
操作基于事务机制,
cusor.rollback()可以将事务回滚到上次提交。
更多信息参见Python DOC
MySQl
使用MySQL需要安装connector,并需要MySQL Server提供数据库服务。这里选用mysqlclient提供MySQL数据库支持,使用
pip install mysqlclient安装。
使用本地MySQL Sever提供服务, 因为Python的DB-API是通用的,操作MySQl的代码与SQLite类似。
import MySQLdb con = MySQLdb.connect(user='testuser', passwd='123456', db='my_test') cursor = con.cursor() cursor.execute('select * from persons') valSet = cursor.fetchall() print(valSet) cursor.close() con.commit() con.close()
相关文章推荐
- python知识库 Orz
- <转>python 发送邮件实例
- 多线程与双端队列结合使用,实现持久化任务(2)
- python3.x+django的mysql驱动安装问题
- Python 随机数生成的几种方法
- python进程、线程、协程
- Python爬虫之Scrapy安装教程
- python---游戏登录
- Python回顾与整理4:序列2—列表与元组
- Python-面向对象
- python字符串连接超过2个,用join代替+号
- Keras - 一个基于 Theano 的深度学习 Python 库
- Python之反射
- python中dir(), hasattr(), getattr(), setattr()的使用
- python中的装饰器Decorator用法
- 第一个python程序
- python函数lambda(), filter(), map(), reduce()
- python装饰器
- python数据分析-处理CSV/EXCEL表格文件
- python常用绘图软件包记录