版权声明:本文为博主原创文章,未经博主允许不得转载。
文章目录
一、单选题
1.1 MySQL Connector 模块
1.1.1 创建连接
1.下列使用 mysql.connector.connect 连接数据库时需要设置( D )参数
A. host,port,count , user,password,database
B. host,port,ip , user,password,database,
C. host,port,user,password,database,table
D. host,port,user,password,database
1.1.3 SQL 注入攻击
2.已连接数据库,下列防止 sql 注入删除 t_user 表的正确代码是( B )
1.1.4 事务控制&异常处理
3.关于事务控制函数,下列描述错误的是( C )【选项中的con为创建的连接】
A. cursor.start_transaction([事务的隔离级别]):开启事务,设置事务级别
B. con.commit():提交该语句之前的所有事务的操作 【提交事务】?????
C. con.rollback():回滚事务
D. connector()对象:提供了简单的事务控制函数
4.已连接数据库,向下图tb_stu表中插入’慕容娜’,‘女’,‘2016-9-11’,18796523654,30,8000,下列选项实现该功能的是( D )
A. 'insert into tb_stu(id,name,sex,enrollment_date,tel,deptno,scholarshi) '\
"values(%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql,('慕容娜','女','2016-9-11',18796523654,30,8000))
B. 'insert into tb_stu(name sex enrollment_date tel deptno scholarship)'\
"values(%s,%s,%s,%s,%s,%s)"
cursor.execute(sql,('慕容娜','女','2016-9-11',18796523654,30,8000))
C. 'insert into tb_stu(name,sex,enrollment_date,tel,deptno,scholarship)'\
"values(%s,%s,%s,%s,%s,%s)"
cursor.execute(sql,('慕容娜','女','2016-9-11',18796523654,'30',8000))
D. 'insert into tb_stu(name,sex,enrollment_date,tel,deptno,scholarship)'\
"values(%s,%s,%s,%s,%s,%s)"
cursor.execute(sql,('慕容娜','女','2016-9-11',18796523654,30,8000))
import mysql.connector
try:
con = mysql.connector.connect(
host='localhost',
port='3306',
user='root',
password='123456',
database='lsj2021_course'
);
# 开启事务
con.start_transaction()
# 创建游标
cursor = con.cursor()
# 执行写入语句
sql = "INSERT INTO t_student(id, name, sex, enrollment_date, tel, tuition, dorm_money, scholarship, deptno) " \
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
cursor.execute(sql, (1001, '刘诗诗', '女', '1965-12-1', '13366886688', '5000', 400, 3500, 10))
# 事务提交
con.commit()
except Exception as e:
if 'con' in dir():
# 事务回滚
con.rollback()
print(e)
finally:
if 'con' in dir():
con.close()
1.1.5 数据库连接池
5.已使用数据库连接池连接到数据库,删除下图食品工程系所有的数据,代码如下:
cursor = con.cursor()
sql = "delete tb_stu,tb_dept from tb_stu join tb_dept on tb_stu.deptno=tb_dept.deptno where tb_dept.dname=%s"
cursor.execute(sql, ('食品工程系',))
6.已使用数据库连接池连接到数据库,创建 dept 表,该表结构同如下图tb_dept表的表结构,代码实现如下:
# 创建游标
cursor = con.cursor()
# 根据查询的表结构创建新表:表和数据一起拷贝
# sql = "CREATE TABLE t_emp_new AS (SELECT * FROM t_emp)"
# 根据查询的表结构创建新表:只创建相同的表结构
sql = "CREATE TABLE t_emp_new LIKE t_emp"
cursor.execute(sql)
# 提交事务
con.commit(