下载并安装MySql Connector
pip install mysql-connector-python
新建test.py
输入
import mysql.connector
若未报错,则安装成功。
demo_mysql_connection.py
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username", # 用户名,如 root
password = "password" # 密码, 如 admin
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor: # 列出已有的数据库
print(x)
输出结果:
(‘information_schema’,)
(‘mysql’,)
(‘performance_schema’,)
(‘sys’,)
demo_mysql_db.py
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username", # 用户名,如 root
password = "password", # 密码, 如 admin
database = "mydatabase" # 连接的数据库名
)
请确认请求连接数据库已存在,否则会报错。
demo_mysql_table.py
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username", # 用户名,如 root
password = "password", # 密码, 如 admin
database = "mydatabase" # 连接的数据库名
)
mycursor = mydb.cursor()
# 建表
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
# mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
# 查看所有表
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
# 删除表
sql = "DROP TABLE customers"
mycursor.execute(sql)
注:在建表时,增加id INT AUTO_INCREMENT PRIMARY KEY
;其中AUTO_INCREMENT
会自动为每一条记录增加id
,从1开始递增;PRIMARY KEY
则是设为主键。
mycursor.execute("ALTER TABLE costomers ADD COLUMN id INT AUTO_INCREMNET PRIMARY KEY")
# 插入一条记录
sql = "INSERT INTO customers (name, adddress) VALUES (%s, %s)"
val = ("Bob", "Beijing")
mycursor.execute(sql, val)
mydb.commit() # 重要,修改表格后需要提交,才会更新
print(mycursor.rowcount, "record inserted.")
# 插入多条记录
sql = "INSERT INTO customers (name, adddress) VALUES (%s, %s)"
val = [
("Alice", "Shanghai"),
("Jack", "Wuhu")
]
mycursor.executemany(sql, val) # 注意这里是 executemany()
mydb.commit() # 提交修改
print(mycursor.rowcount, "records inserted.")
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall() # fetchall() 返回所有结果
for x in myresult:
print(x)
mycursor.execute("SELECT name, address FROM customers")
myresult = mycursor.fetchone() # fetchone() 每次调用 返回一条结果
print(myresult)
sql = "SELECT * FROM customers WHERE name = %s"
val = ("Bob", )
mycursor.execute(sql, val)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
sql = "DELETE FROM customers WHERE address = 'Shanghai'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
sql = "Update customers SET address = 'Hefei' WHERE address = 'Wuhu'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) updated")
W3Schools