一、导入pymysql包:
import pymysql
二、建立MySQL链接:
conn = pymysql.connect(
host='localhost',
user='root',
password='123456',
db='pythonDB',
port=3306,
charset='utf8'
)
三、获取游标cusor
cursor = conn.cursor()
四、使用 execute() 方法运行自己需要的sql
#创建数据库
cursor.execute('CREATE DATABASE IF NOT EXISTS pythonDB DEFAULT CHARSET utf8 COLLATE utf8_general_ci;')
#创建表
cursor.execute('drop table if exists user')
sql = """CREATE TABLE IF NOT EXISTS user(
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(36) NOT NULL,
age int(11) NOT NULL,
PRIMARY KEY (id)
) AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;"""
cursor.execute(sql)
五、关闭游标和链接
cursor.close()
conn.close()