Python之MySQLdb操作数据库
一、python操作数据库1.格式:大概分为三部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
代码
import MySQLdb
conn = MySQLdb.connect(host='192.168.0.180',user='cattle',passwd='cattle',db='cattle')
cur = conn.cursor()#创建连接
reCount = cur.execute('select * from admin')
data = cur.fetchall() #对数据进行操作
cur.close() #关闭连接
conn.close()
print data
print reCount #这个的意思是执行完这条命令影响的条数
结果
((1L, 'n2', 'a2'), (2L, 'n1', 'a1'))
2
1.连接的建立与释放
建立连接时可用connect函数,它返回一个connection类型对象
1
db = MySQLdb.connect(host='192.168.0.180',user='cattle',passwd='cattle',db='cattle')
connect常用的参数:
host:数据库主机名.默认是用本地主机
user:数据库登陆名.默认是当前用户
passwd:数据库登陆的秘密.默认为空
db: 要使用的数据库名.没有默认值
port:MySQL服务使用的TCP端口.默认是3306
charset:数据库编码
如果在数据编码设置正确时,向数据库插入数据出现乱码时,可以设置连接的字符集参数
释放连接时可以用connection类型对象的close方法
1
conn.close()
2.cursor对象
执行SQL语句前要获得一个指定连接的cursor对象,由cursor对象对象执行SQL查询并获得结果
获得cursor对象的方法
1
cur = conn.cursor()
在默认情况下cursor方法返回的是BaseCursor类型对象,BaseCursor类型对象在执行查询后每条记录的结果以列表(list)表示。如果要返回字典(dict)表示的记录,就要设置cursorclass参数为MySQLdb.cursors.DictCursor类
1
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
3.插入、删除、更新、查询等操作
cursor类型提供了execute方法用于执行SQL语句
3.1查询
1
cur.execute('select * from admin')
3.2获取结果
获取结果有三种方式:fetchone、fetchall、fetchmany,返回结果是tuple,tuple中每一个元素对应查询结果中的一条记录
fetchone()返回结果集中的第一条记录
fetchall()返回结果集中的所有记录
fetchmany()返回结果集中的size条记录
3.3插入
由于SQL语句较长所以可以将SQL语句定义成变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import MySQLdb
conn = MySQLdb.connect(host='192.168.0.180',user='cattle',passwd='cattle',db='cattle')
cur = conn.cursor()
sql = "insert into admin (name,address) values(%s,%s)"#name和address相当于key,%s是占位符
params = ('n4','a4') #n4和a4相当于value,写在占位符的位置
reCount = cur.execute(sql,params)
conn.commit() #执行完增加、删除、更改的动作都得执行这步进行提交才能生效
cur.close()
conn.close()
print reCount
3.4删除
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import MySQLdb
conn = MySQLdb.connect(host='192.168.0.180',user='cattle',passwd='cattle',db='cattle')
cur = conn.cursor()
sql = "delete from admin where id = %s"
params = (1)
reCount = cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
print reCount
3.5更改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import MySQLdb
conn = MySQLdb.connect(host='192.168.0.180',user='cattle',passwd='cattle',db='cattle')
cur = conn.cursor()
sql = "update admin set name = %s where id = 8"
params = ('n8')
reCount = cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
print reCount
4.事务
python操作数据库的时候一旦有错误不提交操作,全部都没问题的时候才提交
页:
[1]