当前位置:Gxlcms > 数据库问题 > python关于Mysql操作

python关于Mysql操作

时间:2021-07-01 10:21:17 帮助过:4人阅读

)可以直接插入一条数据,但是想插入多条数据的时候这样做并不方便,此时可以用excutemany()方法,看下面的例子:

import MySQLdb
conn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="123456",db="test",                     port=3306,charset="utf8") 
cur = conn.cursor()
#一次插入多条记录
sql="insert into msg values(%s,%s,%s)"
#executemany()方法可以一次插入多条值,执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
cur.executemany(sql,[
    (‘test05‘,‘zhzhgo05‘,‘test content05‘),
    (‘test06‘,‘zhzhgo06‘,‘test content06‘),
    (‘test07‘,‘zhzhgo07‘,‘test content07‘),
    ])
cur.close()
conn.commit()
conn.close()

如果想要向表中插入1000条数据怎么做呢,显然用上面的方法很难实现,如果只是测试数据,那么可以利用for循环,现有一张user表,字段id自增,性别随机,看下面代码:

import MySQLdb
import random
conn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="",db="test",                     port=3306,charset="utf8")
cur=conn.cursor()
sql="insert into user (name,gender) values"
for i in range(1000):
    sql+="(‘user"+str(i)+"‘,"+str(random.randint(0,1))+"),"
sql=sql[:-1]
print sql
cur.execute(sql)


3.查询数据

执行cur.execute("select * from msg")来查询数据表中的数据时并没有把表中的数据打印出来,如下:

import MySQLdb
conn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="",db="test",                     port=3306,charset="utf8")
cur=conn.cursor()
sql=‘select * from msg‘
n=cur.execute(sql)
print n

此时获得的只是我们的表中有多少条数据,并没有把数据打印出来

介绍几个常用的函数:

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

fetchmany(size=None):接收size条返回结果行,

如果size的值大于返回的结果行的数量,

则会返回cursor.arraysize条数据

fetchone():返回一条结果行

scroll(value,mode=‘relative‘):移动指针到某一行,

如果mode=‘relative‘,则表示从当前所在行移动value条,

如果mode=‘absolute‘,则表示从结果集的第一行移动value条


看下面的例子:

import MySQLdb
conn=MySQLdb.connect(host="127.0.0.1",user="root",                     passwd="",db="test",                     port=3306,charset="utf8")
cur=conn.cursor()
sql=‘select * from msg‘
n=cur.execute(sql)
print cur.fetchall()
print "-------------------"
cur.scroll(1,mode=‘absolute‘)
print cur.fetchmany(1)
print "-------------------"
cur.scroll(1,mode=‘relative‘)
print cur.fetchmany(1)
print "-------------------"
cur.scroll(0,mode=‘absolute‘)
row=cur.fetchone()
while row:
    print row[2]
    row=cur.fetchone()
cur.close()
conn.close()

执行结果如下:

>>> 

((1L, u‘test01‘, u‘zhzhgo01‘, u‘test content01‘), (2L, u‘test02‘, u‘zhzhgo02‘, u‘test content02‘), (3L, u‘test03‘, u‘zhzhgo03‘, u‘test content03‘), (4L, u‘test04‘, u‘zhzhgo04‘, u‘test content04‘))

-------------------

((2L, u‘test02‘, u‘zhzhgo02‘, u‘test content02‘),)

-------------------

((4L, u‘test04‘, u‘zhzhgo04‘, u‘test content04‘),)

-------------------

zhzhgo01

zhzhgo02

zhzhgo03

zhzhgo04

>>> 


本文出自 “今日的努力,明日的成功!” 博客,请务必保留此出处http://zhzhgo.blog.51cto.com/10497096/1678319

python关于Mysql操作

标签:python   mysql   

人气教程排行