PyMysql的基本操作

pymysql是一个python用来连接操作mysql的一个库

安装pymysql库

pip install pymysql

先举个例子

import pymysql
 
db = pymysql.connect("localhost","root","1004210191","first")
cursor = db.cursor()
cursor.execute("select version();")
data = cursor.fetchone()
print("Data version %s" %data)
sql = "insert into employee(ID, 
       first_name, age) 
       values ('%s','%s','%s')" %('5', 'Mohan', 20)
try:
   # 执行sql语句
   cursor.execute(sql)
   # 执行sql语句
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
   
db.close()

以上的例子中进行了两个操作

  1. 查询mysql版本
  2. 向frist数据库里的employee表里每一个字段插入一行数据

具体分析一下:
打开数据库连接

  • db = pymysql.connect(‘localhost’,‘用户名’,‘密码’,‘数据库名称’)

使用cursor()创建一个游标对象,

  • cursor = db.cursor()

使用execute()向数据库发出sql语句请求

sql = "INSERT INTO EMPLOYEE(ID, 
       first_name, age) 
       VALUES ('%s','%s','%s')" %('7', 'Mohan', 20)
try:
   # 执行sql语句
   cursor.execute(sql)
   # 执行sql语句
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
原文地址:https://www.cnblogs.com/yfc0818/p/11072675.html