调用步骤
- 1.cmd 安装:pip install pymysql
- 2.导入:import pymysql
- 3.建立连接:conn = pymysql.connect(user='用户名',password='密码',database='库名',charset='utf8')
- 4.建立游标:cursor()
- 5.查询语句:sql = ('sql语句,所有输入参数用%s表示')
- 6.执行:cursor.execute(sql,(输入参数1,输入参数2......输入参数N))
- 7.查询打印:for (表字段1,表字段2) in cursor: print(表字段1,表字段2)
- 8.提交(新增、修改、删除):conn.commit()
- 9.关闭游标,关闭连接:cursor.close conn.close
安装mysql,创建库,表,增加记录
CREATE DATABASE pytest; USE pytest; CREATE TABLE student( NAME VARCHAR(20), age INT ); DELETE FROM student; INSERT INTO student(NAME,age) VALUES('zhangshan',20); INSERT INTO student(NAME,age) VALUES('lisi',88);
mysqldb.py 文件内容(操作数据库):
#!/usr/bin/python # -*- coding: UTF-8 -*- import pymysql #连接数据库 conn = pymysql.connect(user='root',password='root',database='pytest',charset='utf8') cur = conn.cursor() #不论是什么数据类型,占位符都用%s #带条件查询 sql = ('SELECT * FROM student WHERE NAME =%s AND age =%s') cur.execute(sql,('zhangshan',20)) #不带条件查询 sql = ('SELECT * FROM student') cur.execute(sql) #将只返回一条结果,返回单个元组如('name','age') #data = cur.fetchone() #也将返回所有结果,返回二维元组(tuple),如(('name','age'),('name','age')) data = cur.fetchall() #打印值 for (name,age) in data: print(name,age) #新增 sql=('INSERT INTO student VALUES(%s,%s)') cur.execute(sql,('wangwu',10)) #修改 sql=('UPDATE student SET age=%s WHERE NAME=%s') cur.execute(sql,(20,'wangwu')) #删除 sql=('DELETE FROM student WHERE NAME =%s') cur.execute(sql,('wangwu')) #只要是修改了表内容的操作,后面一定要提交,否则不起作用新增修改删除 conn.commit() conn.close cur.close
来源:https://www.cnblogs.com/yiwenrong/p/12658908.html