import pymysql# 获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库db = pymysql.connect(host="127.0.0.1",user="root",passwd="123456",db="mysql",charset='utf8' )# 使用 cursor()方法创建一个游标对象 cursorcursor = db.cursor()# 使用 execute()方法执行 SQL 查询cursor.execute("SELECT user,host,password from user")# 使用 fetchall()方法获取所有行.data = cursor.fetchall()print(data)cursor.close()#关闭游标db.close()#关闭数据库连接
进行增删改操作示例:
import pymysqldb = pymysql.connect(host='10.3.1.174',user='root',password='123456',db='test')cursor = db.cursor()# SQL 插入数据sql = "INSERT INTO employee (first_name, last_name, age, sex, income) " \ "VALUES ('w', 'Eason', '29', 'M', '8000')"# SQL 更新数据# sql = "UPDATE employee first_name = Wang WHERE first_name = w"# SQL 删除数据# sql = "DELETE FROM employee WHERE age > 20"try: cursor.execute(sql) db.commit()except: db.rollback()db.close()
参考资料 http://www.runoob.com/python3/python3-mysql.html