- import pymysql
- # 创建连接对象
- conn = pymysql.connect(host="localhost", port=3306, user='root', password='******', database='python_sql', charset='utf8')
- cur = conn.cursor() # 获取游标对象
- sql = 'select * from students;' # 查询SQL语句
- rowCount = cur.execute(sql) # 执行SQL语句,返回执行过程中影响的行数
- print('SQL语句执行过程中影响的行数为%d' % rowCount)
- # print(cur.fetchone()) # 取出结果集中的一条数据,输出:(2, 'XY', 20, None, '男', b'\x00', 3)
- for i in cur.fetchall(): # 取出所有数据
- print(i)
- cur.close() # 关闭游标
- conn.close() # 关闭连接
-
- 输出:
- SQL语句执行过程中影响的行数为6
- (2, 'XY', 20, None, '男', b'\x00', 3)
- (3, 'YX', 18, None, '女', b'\x00', 2)
- (4, 'XY', None, None, None, b'\x01', None)
- (7, 'XYY', 18, None, '女', b'\x01', None)
- (8, 'YXX', 18, None, '女', b'\x00', None)
- (9, 'XX', 25, None, None, b'\x01', None)
- import pymysql
- # 创建连接对象
- conn = pymysql.connect(host="localhost", port=3306, user='root', password='******', database='python_sql', charset='utf8')
- cur = conn.cursor() # 获取游标对象
- # try:
- # sql = "insert into students(id,name,age,gender,sid) values(10,'yy', 19, '男', 3);" # 添加
- # sql = "delete from students where id=7;" # 删除
- sql = "update students set age=21 where id=8;" # 修改
- rowCount = cur.execute(sql) # 执行SQL语句,返回执行过程中影响的行数
- print('SQL语句执行过程中影响的行数为%d' % rowCount)
- conn.commit()
- # except Exception as e:
- # conn.rollback() # 撤销上面的SQL操作
- cur.close() # 关闭游标
- conn.close() # 关闭连接
SQL注入:用户提交带有恶意的数据与SQL语句进行字符串方式的拼接,从而影响了SQL语句的语义,最终产生数据泄露的现象
- import pymysql
- def main():
- search_name = input('请输入姓名:')
- # 创建连接对象
- conn = pymysql.connect(host="localhost", port=3306, user='root', password='******', database='python_sql', charset='utf8')
- cur = conn.cursor() # 获取游标对象
-
- # 非安全方式
- # sql = "select * from students where name='%s';" % search_name # 查询SQL语句
- # print('sql语句为%s' % sql)
- # rowCount = cur.execute(sql) # 执行SQL语句,返回执行过程中影响的行数
-
- # 安全方式
- params = [search_name] # 构造参数列表
- rowCount = cur.execute("select * from students where name=%s", params) # 若有多个参数,需参数化,params = [参数1, 参数2....],此时sql语句中有多个%s,其中%s无需带引号
-
- print('SQL语句执行过程中影响的行数为%d' % rowCount)
- # result = cur.fetchone()
- result = cur.fetchall()
- print('查询结果为:\n', result)
- cur.close() # 关闭游标
- conn.close() # 关闭连接
-
- if __name__ == '__main__':
- main()
-
- 输出:
- ------------------------------------------非安全方式--获取一条数据-------------------------
- 请输入姓名:XY
- sql语句为select * from students where name='XY';
- SQL语句执行过程中影响的行数为2
- 查询结果为:
- (2, 'XY', 20, None, '男', b'\x00', 3)
- ------------------------------------------安全方式--获取所有------------------------------
- 请输入姓名:XY
- SQL语句执行过程中影响的行数为2
- 查询结果为:
- ((2, 'XY', 20, None, '男', b'\x00', 3), (4, 'XY', None, None, None, b'\x01', None))
- -----------------------------------------------------------------------------------------
学习导航:http://xqnav.top/