python|python pymysql模块对mysql进行增删改查

python语言开发过程中,用pymysql模块执行mysql数据库的增删改查操作,以下用简单的例子做一下操作的记录,这些操作的前提是已安装好mysql数据库及安装好pymysql模块,如没有安装对应模块,可用 pip install pymysql 安装(好记性不如烂笔头)
1:数据的添加

# -*- coding: utf-8 -*- ''' author:he qq:760863706 date:2018-9-12 ''' import pymysql import time #连接数据库,库名:py_test db = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='',db='py_test') #创建游标 cursor = db.cursor() timestamp = int(time.time()) #执行数据库操作 插入单条数据 sql = 'insert into user(name,age,create_time) values(%s,%s,%s)' data = https://www.it610.com/article/('name_1',1,timestamp) cursor.execute(sql,data) db.commit() #执行数据库操作 插入多条数据 # sql = 'insert into user(name,age,create_time) values(%s,%s,%s)' # data = https://www.it610.com/article/[('name_2',2,timestamp),('name_3',3,timestamp),('name_4',4,timestamp)] # cursor.executemany(sql,data) # db.commit() #关闭数据库连接 cursor.close() db.close()

2:数据的更新
# -*- coding: utf-8 -*- ''' author:lihe qq:760863706 date:2018-9-12 ''' import pymysql import time #连接数据库 db = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='',db='py_test') #创建游标 cursor = db.cursor() timestamp = int(time.time()) #执行数据库操作 插入单条数据 sql = 'update user set name=%s,age=%s where id=%s' data = https://www.it610.com/article/('name_1_update',11,1) cursor.execute(sql,data) db.commit() #关闭数据库连接 cursor.close() db.close()

3:数据的查询
# -*- coding: utf-8 -*- ''' author:lihe qq:760863706 date:2018-9-12 ''' import pymysql #连接数据库 db = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='',db='py_test') #创建游标 cursor = db.cursor() #根据不同的查询条件获取数据 sql = 'select * from user' cursor.execute(sql) # sql = 'select * from user where id in%s' # data=https://www.it610.com/article/[(1,2)] # cursor.execute(sql,data) #打印第一条数据 print(cursor.fetchone()) #打印全部数据 print(cursor.fetchall()) #打印数据总条数 print(cursor.rowcount) #关闭数据库连接 cursor.close() db.close()

【python|python pymysql模块对mysql进行增删改查】4:数据的删除
# -*- coding: utf-8 -*- ''' author:lihe qq:760863706 date:2018-9-12 ''' import pymysql #连接数据库 db = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='',db='py_test') #创建游标 cursor = db.cursor() #根据sql条件删除对应数据 sql = 'delete from user where id=%s' data=https://www.it610.com/article/(1) cursor.execute(sql,data) db.commit() #关闭数据库连接 cursor.close() db.close()

    推荐阅读