您的位置:首页 > 编程语言 > Python开发

Python 数据库

2016-03-20 11:58 489 查看
python内置了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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: