Python连接并操作MySql数据库

文章目录

  • 准备
    • 测试
  • 使用
    • 建立连接并查看所有数据库
    • 连接指定数据库
    • 建表 查看所有表 删除表
    • 增加字段
    • 插入记录
    • 查询记录
      • WHERE 筛选
    • 删除记录
    • 更改记录
  • 参考


准备

下载并安装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)

WHERE 筛选

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

你可能感兴趣的:(数据库,mysql,python)