Python之MySQLdb操作数据库-创新互联

一、python操作数据库

创新互联公司是一家专业提供喀喇沁企业网站建设,专注与成都网站建设、网站制作、HTML5建站、小程序制作等业务。10年已为喀喇沁众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。

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])返回结果集中的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操作数据库的时候一旦有错误不提交操作,全部都没问题的时候才提交

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


名称栏目:Python之MySQLdb操作数据库-创新互联
文章出自:http://myzitong.com/article/ccgigi.html