前言
- pymsql是Python中操作MySQL的模块
- 程序在运行时,数据都是在内存中的。当程序终止时,通常需要将数据保存在磁盘上。
安装模块
pip install PyMySql
基本使用
connect = pymysql.connect(host='127.0.0.1',
user='root',
password='pwd',
database='database_name')
start = connect.cursor()
cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
cursor.scroll(1,mode='relative')
cursor.scroll(2,mode='absolute')
start.execute()
start.executemany()
dp = start.fetchone()
dp = start.fetchall()
dp = start.fetchone(3)
db.close()
具体实例之查询select
import pymysql
connect = pymysql.connect(host='127.0.0.1',
user='root',
password='pwd',
database='database_name')
cursor = connect.cursor()
table_name = 'school_info_table'
sql = "SELECT * FROM %s WHERE schoolname LIKE '%深圳%' " % table_name
try:
cursor.execute(sql)
result = cursor.fetchall()
print(result)
except Exception as e:
connect.rollback()
print("select Fail")
print(e)
finally:
cursor.close()
connect.close()
具体实例之修改update
import pymysql
connect = pymysql.connect(host='127.0.0.1',
user='root',
password='pwd',
database='database_name')
cursor = connect.cursor()
table_name = 'table_name '
user_id = 'yyy'
user_no = 'xxx'
sql = "UPDATE %s SET user_no = '%s' WHERE user_id = '%s'" % (table_name, user_no, user_id)
try:
cursor.execute(sql)
connect.commit()
print("update success")
except Exception as e:
connect.rollback()
print("update fail")
print(e)
finally:
cursor.close()
connect.close()