安装
pip install mysqlclient
前置准备:
Debian / Ubuntu
$ sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
Red Hat / CentOS
% sudo yum install python3-devel mysql-devel
使用
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
# 创建游标
cur = conn.cursor()
# 执行 sql 语句
cur.execute("select * from raw_data.xxx")
# 关闭游标
cur.close()
# 提交
conn.commit()
# 关闭连接
conn.close()
# 插入多行 - 使用 cur.executemany
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
('3','Tom','1 year 1 class','6'),
('3','Jack','2 year 1 class','7'),
('3','Yaheng','2 year 2 class','7'),
])
# 获取数据
aa=cur.execute("select * from student")
info = cur.fetchmany(aa)
for ii in info:
print(ii)
参考文章:https://www.cnblogs.com/fnng/p/3565912.html