使用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

相關文章
相關標籤/搜索