python3安装pymysql连接mysql数据库
一、python3安装mysql
pip install pymysql
二、连接数据库操作
import pymysql
db=pymysql.connect(“localhost”,”root”,”123456”,"数据库名")
# 创建游标对象
cursor = db.cursor()
# 执行sql语句
cursor.execute(“select version()”)
# 获取返回结果集的第一个行数据,返回元组(fetchall()返回结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回)
data = cursor.fetchone()
# 打印结果
print(“数据库版本是%s”%data)
# 最后执行完毕关闭游标对象和数据库
cursor.close()
db.close()
# 连接mysql数据库
self.db = pymysql.connect(host='localhost',port=3306,user='root',passwd='123456')
# 创建游标对象
self.cursor = self.db.cursor()
# 如果没有则创建python4数据库,如果已经创建好再次执行会有warning警告,所以需要提前创建好数据库
# self.db = pymysql.connect(host='localhost',port=3306,user='root',passwd='123456',db='python4')
self.cursor.execute('CREATE database if not EXISTS python4 default charset utf8 COLLATE utf8_general_ci;')
self.cursor.execute("use python4;")
# 如果没有则创建books表,如果已经创建好再次执行会有warning警告,所以需要提前创建好表
sql = """
CREATE TABLE IF not exists books(id int(11) not null auto_increment PRIMARY KEY,
book_name VARCHAR(200) not null,
author VARCHAR(200),
image_url VARCHAR(300),
book_info VARCHAR(800))ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
self.cursor.execute(sql)
# 插入数据
self.cursor.execute(
"""INSERT INTO books(book_name, author, image_url, book_info)VALUES(%s, %s, %s, %s)""",(book['book_name'], book['author'], book['image_url'], book['book_info']))
self.db.commit()
self.cursor.close()
self.db.close()