操作mysql数据库源码_python操作MySQL数据库源码实例

我采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧:

1

2

3

4

5

6

7

8

9

10

import MySQLdb

try:

conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)

cur=conn.cursor()

cur.execute('select * from user')

cur.close()

conn.close()

except MySQLdb.Error,e:

print "Mysql Error %d: %s" % (e.args[0], e.args[1])

请注意修改你的数据库,主机名,用户名,密码。

下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

import MySQLdb

try:

conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)

cur=conn.cursor()

cur.execute('create database if not exists python')

conn.select_db('python')

cur.execute('create table test(id int,info varchar(20))')

value=[1,'hi rollen']

cur.execute('insert into test values(%s,%s)',value)

values=[]

for iin range(20):

values.append((i,'hi rollen'+str(i)))

cur.executemany('insert into test values(%s,%s)',values)

cur.execute('update test set info="I am rollen" where id=3')

conn.commit()

cur.close()

conn.close()

except MySQLdb.Error,e:

print "Mysql Error %d: %s" % (e.args[0], e.args[1])

请注意一定要有conn.commit()这句来提交事务,要不然不能真正的插入数据。

运行之后我的MySQL数据库的结果就不上图了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

import MySQLdb

try:

conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)

cur=conn.cursor()

conn.select_db('python')

count=cur.execute('select * from test')

print 'there has %s rows record' % count

result=cur.fetchone()

print result

print 'ID: %s info %s' % result

results=cur.fetchmany(5)

for rin results:

print r

print '=='*10

cur.scroll(0,mode='absolute')

results=cur.fetchall()

for rin results:

print r[1]

conn.commit()

cur.close()

conn.close()

except MySQLdb.Error,e:

print "Mysql Error %d: %s" % (e.args[0], e.args[1])

运行结果就不贴了,太长了。

查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定:

在Python代码

conn = MySQLdb.Connect(host=’localhost’, user=’root’, passwd=’root’, db=’python’) 中加一个属性:

改为:

conn = MySQLdb.Connect(host=’localhost’, user=’root’, passwd=’root’, db=’python’,charset=’utf8′)

charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset=’gb2312′。

下面贴一下常用的函数:

然后,这个连接对象也提供了对事务操作的支持,标准的方法

commit() 提交

rollback() 回滚

cursor用来执行命令的方法:

callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数

execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数

executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数

nextset(self):移动到下一个结果集

cursor用来接收返回值的方法:

fetchall(self):接收全部的返回结果行.

fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.

fetchone(self):返回一条结果行.

scroll(self, value, mode=’relative’):移动指针到某一行.如果mode=’relative’,则表示从当前所在行移动value条,如果 mode=’absolute’,则表示从结果集的第一行移动value条.

use master go if exists(select*from sysdatabases where name='bbsDB') drop database bbsDB create database bbsDB on primary ( name='bbsDB_data', filename='D:\project\bbsDB_data.mdf', size=10mb ) log on ( name='bbsDB_log', filename='D:\project\bbsDB_log.ldf', size=10mb ) go use bbsDB go create table bank ( customerName char(8) not null,--顾客姓名 cardID char(10) not null,--卡号 currentMoney Money not null,--当前余额 ) go create table transInfo ( cardID char(10) not null,--卡号 transType char(4) not null,--交易类型 transMoney money not null,--交易金额 transDate datetime not null,--交易时间 ) go alter table bank add constraint ck_currentMoney check(currentMoney>=1) alter table transInfo add constraint df_transDate default(getDate())for transDate,constraint ck_transType check(transType in('存入','支取')) go insert into bank(customerName,cardID,currentMoney)values('张三','100010001',2000) --insert into bank(customerName,cardID,currentMoney)values('李四','100010002',1) print '------取款前的余额------' select*from bank go begin transaction declare @errorSum int declare @myMoney Money set @myMoney=1000 --取款金额 set @errorSum=0 --取款 insert into transInfo(cardID,transType,transMoney)values('100010001','支取', @myMoney) set @errorSum=@errorSum+@@error update bank set currentMoney=currentMoney-@myMoney where cardID='100010001' set @errorSum=@errorSum+@@error print'------取款事务过程中余额和交易信息------' select*from bank select*from transInfo if @errorSum<>0 begin print'交易失败,回滚事务' rollback transaction end else begin print '交易成功,提交事务' commit transaction end go print'-------取款事务结束后的余额和交易信息------' select*from bank select*from transInfo go go begin transaction declare @errorSum int declare @myMoney Money set @myMoney=5000 --存入金额 set @errorSum=0 --存入 insert into transInfo(cardID,transType,transMoney)values('100010001','存入',@myMoney) set @errorSum=@errorSum+@@error update bank set currentMoney=currentMoney+@myMoney where cardID='100010001' set @errorSum=@errorSum+@@error print'------存款事务过程中余额和交易信息------' select*from bank select*from transInfo if @errorSum<>0 begin print'交易失败,回滚事务' rollback transaction end else begin print '交易成功,提交事务' commit transaction end go print'-------存款事务结束后的余额和交易信息------' select*from bank select*from transInfo go
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值