mysql.connector 是mysql官方提供的驱动器,可使用pip进行安装
pip install mysql-connector
创建一张mysql表
create table city(
id int NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
接下来,向这张表里写入数据
import mysql.connector
mydb = mysql.connector.connect(
host="your ip", # 数据库主机地址
user="username", # 数据库用户名
passwd="password", # 数据库密码
port=6606,
database='flink_db'
)
sqls = [
"insert into city(name)values('北京')",
"insert into city(name)values('上海')",
"insert into city(name)values('广州')",
"insert into city(name)values('深圳')",
]
mycursor = mydb.cursor()
for sql in sqls:
mycursor.execute(sql)
mydb.commit()
insert 语句会向表里新增数据,数据库有变动,必须执行commit,否则不会生效。
QQ交流群: 211426309