一、创建数据库及表
CREATE DATABASE testdb; USE testdb; CREATE TABLE `tb_user` ( `id` INT (11) NOT NULL AUTO_INCREMENT, `userName` VARCHAR (18) DEFAULT NULL, `birth` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) );
二、连接数据库并操作
import pymysql conn = pymysql.connect(host='127.0.0.1', user = "root", passwd="root", db="testdb", port=3306, charset="utf8") cur = conn.cursor() #sql语句 sql = "insert into tb_user(userName, birth) value(%s, %s)" #数据 person = [['小军', '1993-06-05'], ['小明', '1993-04-03']] for i in range(len(person)): param = tuple(person[i]) #执行sql语句 count = cur.execute(sql, param) #判断是否成功 if count > 0: print("添加数据成功! ") #提交事务 conn.commit() #查询数据 cur.execute("select * from tb_user") #获取数据 users = cur.fetchall(); for i in range(len(users)): print(users[i]); #关闭资源连接 cur.close() conn.close() print("数据库断开连接!");
三、执行结果
数据库里面数据
-------------------- 额外内容 --------------------
1、提示 ModuleNotFoundError: No module named 'pymysql' 错误解决方法
安装pymysql模块:
pip3 install pymysql