一:两个对象 connection 与 cursor
调用connect()方法创建 connection对象:
connection = pymysql.connect(args)
connection对象方法与属性介绍:
close() Send the quit message and close the socket.
commit() Commit changes to stable storage.
cursor(cursor=None) Create a new cursor to execute queries with.
open Return True if the connection is open
begin() Begin transaction;
ping(reconnect=True) Check if the server is alive.
rollback() Roll back the current transaction.
select_db(db) Set current db.
show_warnings() Send the “SHOW WARNINGS” SQL command
cursor对象是用来与数据库进行交互的;通过connection对象调用cursor()方法创建cursor对象
cursor = connection.cursor() # cursor = connection.cursor(cursor = pymysql.cursors.DictCursor)
cursor对象方法与属性介绍:
close() Closing a cursor just exhausts all remaining data.
execute(query, args=None) Execute a query ;Return: Number of affected rows (a int number)
# If args is a list or tuple, %s can be used as a placeholder in the query.
# If args is a dict, %(name)s can be used as a placeholder in the query.
executemany(query, args) Run several data against one query
fetchall() Fetch all the rows
fetchmany(size=None) Fetch several rows
fetchone() Fetch the next row
二:代码与笔记
import pymysql #导入pymysql模块 connection = pymysql.connect(host='127.0.0.1', user='user', password='pwd', database='db', # 也有用 db='db' ,是数据库的别名,为了兼容MySQLdb charset='utf8', # 可选 cursorclass=pymysql.cursors.DictCursor, # 可选,这种cursor会以字典的形式返回查询结果 autocommit=True) # 可选 设置为自动提交;默认autocommit=False cursor = connection.cursor() # 产生cursor对象,该对象用来与数据库进行交互 sql = 'insert into t1(name,password) values(%s,%s);' cursor.execute(sql,('rock','123')) # connection.commit() 若无设置autocommit=True,则需要在这提交以保存你的修改 sql1 = 'select * from t1;' rows = cursor.execute(sql1) # 执行一条查询,返回受影响的行数,而不是查询结果 res = cursor.fetchall() # 取出所有的查询结果 cursor.close() # 需先关闭cursor connection.close() # 最后要关闭connection # with connection.cursor() as cursor: # 采用这种方式最后会自动关闭cursor,所以无需再用cursor.close() # sql = 'select * from t1;' # rows = cursor.execute(sql) # res = cursor.fetchall() # 选用pymysql.cursors.DictCursor 以字典的形式返回查询结果 # 如 {'name': '程咬铁', 'sex': 'female'} 形式为 {列名:列值,列名:列值} # 注意:查询结果中的每条记录只能被取一次,所有记录取完了再取就会取空(None 或 空列表) # fetchone() 从查询结果中取出下一条记录 # fetchmany(size=None) 从查询结果中取出几条记录,放入一个列表中;不设置size,默认取出下一条记录 # fetchall() 从查询结果中取出所有记录,放入一个列表中