数据库编程(python+mysql)
流程:
- 使用pymysql模块
- 建立连接:
con = connect(host='localhost',port=3306,user='dbuser1',password='',database='dbname',charset='utf8')
- 获取游标:
cur = con.cursor()
- 执行sql:
cur.execute('要执行的sql语句') #会返回一个受影响行数的数字
- 如果是select语句,可用cur.fetchone(),cur.fetchmany(2),cur.fetchall()获取查询的数据,返回值是元组类型。这里要注意的是在一次查询中前面的取过了就不会再取,因为游标是移动的
- 数据有变化时提交:
con.commit()
- 撤销,回滚:
con.rollback()
- 关闭游标:
cur.close()
- 关闭连接:
con.close()
sql注入
- 如在需要用户输入作为参数传递给sql语句时,用户有可能输入or连接符,此时拿到输入数据传递给sql语句时就会产生sql注入的问题,如下:
find_id = input('请输入要查询的id')
sql = 'select * from t_table1 where id = %s;' %find_id
cur.execute(sql)
- 此时如果用户输入1 or 2,sql会拼接为:select * from t_table1 where id = 1 or 2;这条语句会查询出所有的数据
- 解决办法为给execute传入另外一个参数,该参数是元组形式,传入的值为需要传递的输入值
sql = 'select * from t_table1 where id = %s;' #不再在这里格式化字符串
cur.execute(sql,(find_id,))