pymysql
- Pip 安装 pymysql
pip install pymysql
- 简单查询
import pymysql # 导入pymysql mysql_conn = pymysql.connect(host="127.0.0.1", # 连接数据库 port=3306, user="root", password="", charset="utf8", db="userinfo") c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor获取操作游标,DictCursor以字典形式输出,默认是元组 sql = "select * from users WHERE name='小黑' and age=17" # sql语句 users 数据库表名c.execute(sql) # 执行sql语句
c.execute(sql) print(c.fetchall()) # 获取所有记录 c.close() # 关闭连接 mysql_conn.close()
- 结果
[{'id': 2, 'name': '小黑', 'age': 17}]
- 简单插入
import pymysql mysql_conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="", charset="utf8", db="userinfo") c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor) sql = "insert into users(id,name,age) value(4,'小王',20) " c.execute(sql) mysql_conn.commit() c.close() mysql_conn.close()
- 更新
import pymysql mysql_conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="", charset="utf8", db="userinfo") c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor) sql = "update users set name ='%s' where id = %d" c.execute(sql % ("小红",4)) mysql_conn.commit() c.close() mysql_conn.close()
- 删除
import pymysql mysql_conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="", charset="utf8", db="userinfo") c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor) sql = "delete from users where id = %d" c.execute(sql % (4)) mysql_conn.commit() c.close() mysql_conn.close()