本期参考文献: 链接
1、安装mysql可以参考链接: 文章
2、安装mysql与python的工具
进行校验,查看是否安装成功
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE ck") 执行语句创建库
1、使用create创建表
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="westos",
auth_plugin='mysql_native_password',
database='ck'
)
mycurson=mydb.cursor()
mycurson.execute("create table customers (name varchar(255),address varchar(255) )")
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="westos",
auth_plugin='mysql_native_password',
database='ck'
)
mycurson=mydb.cursor()
mycurson.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
INSERT INTO
对刚才建立表格进行插入
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="westos",
auth_plugin='mysql_native_password',
database='ck'
)
mycurson=mydb.cursor()
sql = "INSERT INTO customers (name ,address) values('ck1','china1') " 插入的语法
mycurson.execute(sql)
mydb.commit()
结果显示成功插入
如果插入多个数据可以用executemany
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="westos",
auth_plugin='mysql_native_password',
database='ck'
)
mycurson=mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycurson.executemany(sql, val)
mydb.commit()
1、使用select查询表格的全部内容
fetchall()语法可以获取所有内容
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="westos",
auth_plugin='mysql_native_password',
database='ck'
)
mycurson=mydb.cursor()
mycurson.execute('SELECT * FROM customers')
results = mycurson.fetchall()
for x in results:
print(x)
2、查询某个列
select后跟某个列名
3、查询某一行
使用fetchone()只显示某行
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="westos",
auth_plugin='mysql_native_password',
database='ck'
)
mycurson=mydb.cursor()
mycurson.execute('SELECT name,address FROM customers')
results = mycurson.fetchone()
for row in results:
print(row)
4、筛选表格
使用where筛选
5、使用通配符筛选
%xx%代表对xx相关的内容都进行显示
注意为了防止sql注入,使用安全查询方式
7、排序
使用 ORDER BY 语句按升序或降序对结果进行排序。
ORDER BY 关键字默认按升序对结果进行排序。若要按降序对结果进行排序,请使用 DESC 关键字。