1. 连接数据库
一般python3可以使用mysql.connector和pymysql来连接mysql数据库。
这里使用的是pymysql。
- 首先导入pymysql库
import pymysql
- 然后加载导入的库
%load_ext sql
- 第一种方式:魔术语句。这种方式的缺点在于没有显式的获取到数据库的conn
%sql mysql+pymysql://你的数据库用户:你的数据库用户@localhost/你要使用的数据库名
- 获取到conn的数据库连接方式
conn = pymysql.connect(
host='127.0.0.1',
user='你的数据库用户t',
password='你的数据库用户',
database='你要使用的数据库名',
charset="utf8"
)
这样就获取到了数据库的连接了,接下来就可以对数据库的表进行操作。
2. 对表的一些常用操作
2.1 创建表
%%sql
CREATE TABLE IF NOT EXISTS customers(
cust_id int NOT NULL AUTO_INCREMENT,
cust_name varchar(50) NOT NULL,
cust_email varchar(50) NULL,
cust_city varchar(50) NULL,
cust_country varchar(50) NULL,
PRIMARY KEY (cust_id)
);
2.2 删除表
%%sql
DROP TABLE customers;
3. 对表中的数据进行操作
3.1 插入操作
3.1.1 插入完整的一行
同时数据直接写在代码中
%%sql
INSERT INTO customers
VALUES(NULL,
'Animy',
'000',
'Los Angeles',
'America');
3.1.2 插入一行的一部分
%%sql
INSERT INTO customers(
cust_name,
cust_email,
cust_city,
cust_country)
VALUES(
'Bob',
'001',
'New York',
'America');
3.1.3 插入多行
- 假如是数据包含在代码中,则可以提交多个单独insert语句,也可以组合insert语句,VALUES后的参数之间通过逗号连接
%%sql
INSERT INTO customers(
cust_name,
cust_email,
cust_city,
cust_country)
VALUES(
'Bob',
'001',
'New York',
'America'),
(
'Animy',
'000',
'Los Angeles',
'America');
-
如果数据在表格中,要进行批量插入
-
数据量小时,可以像插入多行数据那样,用insert语句一条条插入
-
数据量大时,可以通过loaddata方法导入
-
load data的详解可以看
https://blog.csdn.net/longzhoufeng/article/details/112377942
LOAD DATA LOCAL INFILE '文件的绝对路径/cust_order_test.csv'
REPLACE INTO TABLE customers
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(cust_name,cust_email,cust_city,cust_country);
3.1.4 插入select查询的结果
假设custnew具有和customer一样的表结构
%%sql
insert into customers(
cust_name,
cust_email,
cust_city,
cust_country
)select cust_name,
cust_email,
cust_city,
cust_country
from custnew
3.2 查询操作
%sql select * from customers
3.3 更改操作
%%sql
UPDATE customers SET cust_email = 'xxx@email.com'
WHERE cust_name = 'xxx';
3.4 删除操作
- 删除所有行
%sql DELETE FROM customers
这种没有where子句的update和delete语句很危险,稍不注意,就会错误的删除表中所有行,所以不要省略WHERE子句
- 删除特定的行
选出cust_id大于1的
%sql DELETE FROM customers WHERE cust_id >= 1;