使用python访问数据库

python中使用mysql的步骤

python中使用数据库可以想象作一个去河对岸工作的小故事

  1. 创建桥梁(connection链接)
  2. 创建工人(curser游标对象)
  3. 工作
  4. 若要获得对岸的东西(查询数据库中数据),就要卸货(输出数据)
  5. 收回工人
  6. 拆除桥梁

访问数据库的程序

要想在python中访问数据库,需要导入pymysql模块
要想创建桥梁(connection链接)对象,需要connect类调用以下参数

conn=connect(参数列表)

* 参数host:连接的mysql主机,如果本机是'localhost'
* 参数port:连接的mysql主机的端口,默认是3306
* 参数database:数据库的名称
* 参数user:连接的用户名
* 参数password:连接的密码
* 参数charset:通信采用的编码方式,推荐使用utf8

利用python查询数据库

假设我们要访问(python库,students表)中的数据

import pymysql
# 创建connection桥梁对象
conn = connect(	host = 'localhost',
				port = 3306,
				database = 'python'
				user = 'root'
				password = '123456'
				charset = 'utf8')
# 创建curser工人对象
curser = conn.curser()
# 编写sql语句
sql = 'select * from students;'
# 工人工作
curser.execute(sql)
# 返回数据,也可以用fatchone,每用一次返回一行。
for i in curser.fatchall():
	print(i)
# 回收工人
curser.close()
# 回收桥梁
conn.close()

利用python对数据库进行增删改

import pymysql
# 创建链接
conn = connect(	host = 'localhost',
				port = 3306,
				database = 'python'
				user = 'root'
				password = '123456'
				charset = 'utf8')
# 创建游标对象
curser = conn.curser()
# 编写sql语句
sql1 = "delete from students where id = 5;"
sql2 = insert into students(name) values ('小明');
sql3 = 'update students set cls_id=2 where id = 4;'
# 执行sql语句
curser.execute(sql1)
curser.execute(sql2)
curser.execute(sql3)
# 确认保存
conn.commit()
# 若要反悔,则可回滚到原来状态
# conn.rollback()
# 关闭游标
curser.close()
# 关闭链接
conn.close()

参数化列表,防sql注入

sql注入

再python中编写查询sql程序的时候,会需要用到定义一个变量接收要查询的内容,然后,再把变量传入sql语句中。如:

name = '小明'
sql = "select * from students where name = '%s' " % name

这样的话,就很容易造成sql注入而泄露数据。如,在输入name时输入' or 1 or '
这样的话,sql语句就变成了select * from students where name = '' or 1 or ''
解析这句话,条件是:

  • where name = ’ ’ 或者 where 1 或者 where ’ ’
    其中,where 1 即表示 True,所以将会输出所有信息。

防sql注入

把name放到一个列表中,再传入sql语句即可。

name = '小明'
sql = "select * from students where name = '%s' % [name]

猜你喜欢

转载自blog.csdn.net/washing1127/article/details/83547082