使用PyMysql调用Mysql数据库示例

# 导入pymysql模块
import pymysqlmysql

# 链接database
conn = pymysql.connect(
host="localhost",
user="root",
password="123456",
database="fanis",
charset="utf8"
)sql

# 获取一个光标
cursor = conn.cursor()
sql = "show tables;"
cursor.execute(sql)
for tables in cursor.fetchall():
for table in tables:
if table == "user":
sql = "drop table user;"
cursor.execute(sql)fetch

# 建立表
sql = """
CREATE TABLE user(
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
);"""
cursor.execute(sql)code

# 插入数据
sql = "insert into user(name, age) values('july', 14);"
cursor.execute(sql)
sql = "insert into user(name, age) values('june', 25);"
cursor.execute(sql)
sql = "insert into user(name, age) values('marin', 36);"
cursor.execute(sql)
sql = "select * from user;"
cursor.execute(sql)
for item in cursor.fetchall():
print(item)rem

# 涉及写操做要注意提交
conn.commit()it

# 关闭链接
cursor.close()
conn.close()table

相关文章
相关标签/搜索