1.创建数据库
db = pymysql.connect(host='localhost', user='root', passwd='your password', port=3306)
cursor = db.cursor()
cursor.execute("CREATE DATABASE Test DEFAULT CHARACTER SET utf8")
db.close()
2.连接数据库,创建表
db = pymysql.connect(host='localhost', user='root', passwd='your password', port=3306, db='Test')
cursor = db.cursor()
sql = 'CREATE TABLE IF NOT EXISTS mydata (id VARCHAR(255) NOt NULL,name VARCHAR(255) NOT NULL ,age VARCHAR (255) NOT NULL)'
cursor.execute(sql)
db.close()
3.向数据库中插入数据
data={"id":01,"name":Jack,"age":12}
db = pymysql.connect(host='localhost', user='root', passwd='your password', port=3306, db='Test', autocommit=True)
cursor = db.cursor()
table = 'mydata'
keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
try:
if cursor.execute(sql, tuple(data.values())):
print("successful!")
db.commit()
except:
print('数据插入失败!')
db.rollback()
db.close()
db = pymysql.connect(host='localhost', user='root', passwd='your password', port=3306, db='Test',autocommit =True)
cursor = db.cursor()
sql = 'INSTER INTO mywifi(id,name,age) values(%s,%s,%s)' % (id, name, age)
cursor.execute(sql, (id,name,age))
db.commit()
db.close()
print("数据插入成功")
4.从数据库中读取并显示数据
db = pymysql.connect(host='localhost', user='root', passwd='your password', port=3306, db='Test', autocommit=True)
cursor = db.cursor()
sql = "SELECT * FROM mydata"
cursor.execute(sql)
mydata = cursor.fetchall()
pdate = pd.read_sql(sql, db)
print(pdate)
db.close()