python使用mysql数据库-----pymysql模块

基本步骤

1、创建连接数据库对象

1 message = {
2             "host":host,         
3             "user":user,
4             "password":db_pwd,
5             "database":db_name,
6             "autocommit":True    #设置自动提交修改
7             }
8 db = pymysql.connect(**message)   #pymysql.connect()数据库连接

2、创建数据库操作游标

cursor = db.cursor()

3、执行sql语句

1 sql1 = "select * from users where username = '%s'"%username
2 row = cursor.execute(sql1)     #返回值返回查询到的条数  

扩展:使用cursor.execute()执行插入语句时,只能插入一条数据
   使用cursor.executemany()可同时插入多条数据,要用列表形式插入[(),(),()],列表中存放元组

例:message_list = [('Amy',12),('Tom',13)]
  rows = cursor.executemany(sql,message_list) #sql:插入语句

4、如果创建连接数据库对象时没有设置autocommit=True,则需手动提交修改

db.commit()    #db:数据库连接对象

5、获取SQL执行结果

(1)fetchone()     # 一次一条数据

(2)fetchall()     #一次读取全部数据,如果没有数据,则返回空元组或列表

(3)fetchmany()    #一次多条数据,括号内填入要读取的数据条数,默认为1,如果读数超过实际条数,则显示实际条数


扩展:如果想将返回值以字典形式显示,则在创建游标时设置:

   cursor
= db.cursor(pymysql.cursor.DictCursor)

6、关闭游标

cursor.close()

7、关闭数据库连接

db.close()
原文地址:https://www.cnblogs.com/chunqiu666/p/12750857.html