PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,
Python2中则使用MySQLdb。
数据库查询操作
01_python数据库编程基本操作.py
import pymysql
#1). 创建数据库连接, autocommit是否自动提交修改到数据库中.
conn = pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘westos‘,
db=‘Blog‘, port=3306, autocommit=True, charset=‘utf8‘)
#2). 创建游标(用来执行sql语句的)
cur = conn.cursor()
#3). 执行sql语句
insert_sql = ‘insert into users(username) values ("user6");‘
cur.execute(insert_sql)
print("插入数据成功.......")
#4). 关闭游标
cur.close()
#5).关闭连接
conn.close()
02_python数据库编程基本操作.py
class Connection(object):
def __enter__(self):
Context manager that returns a Cursor
warnings.warn(
"Context manager API of Connection object is deprecated; Use conn.begin()",
DeprecationWarning)
return self.cursor()
def __exit__(self, exc, value, traceback):
On successful exit, commit. On exception, rollback(回滚)
if exc:
self.rollback()
else:
self.commit()
import pymysql
#使用with语句是, pymysql.connect返回的是数据库游标。(具体的内容查看源代码)
with pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘westos‘,
db=‘Blog‘, port=