当前位置:Gxlcms > 数据库问题 > python操作MySQL数据库

python操作MySQL数据库

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

 1 import MySQLdb
 2  
 3 try:
 4     conn=MySQLdb.connect(host=localhost,user=root,passwd=root,db=test,port=3306)
 5     cur=conn.cursor()
 6     cur.execute(select * from user)
 7     cur.close()
 8     conn.close()
 9 except MySQLdb.Error,e:
10      print "Mysql Error %d: %s" % (e.args[0], e.args[1])

插入数据,批量插入数据,更新数据!

 

 1 import MySQLdb
 2  
 3 try:
 4     conn=MySQLdb.connect(host=localhost,user=root,passwd=root,port=3306)
 5     cur=conn.cursor()
 6      
 7     cur.execute(create database if not exists python)
 8     conn.select_db(python)
 9     cur.execute(create table test(id int,info varchar(20)))
10      
11     value=[1,hi rollen]
12     cur.execute(insert into test values(%s,%s),value)
13      
14     values=[]
15     for i in range(20):
16         values.append((i,hi rollen+str(i)))
17          
18     cur.executemany(insert into test values(%s,%s),values)
19  
20     cur.execute(update test set info="I am rollen" where id=3)
21  
22     conn.commit()
23     cur.close()
24     conn.close()
25  
26 except MySQLdb.Error,e:
27      print "Mysql Error %d: %s" % (e.args[0], e.args[1])

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

 

 1 import MySQLdb
 2  
 3 try:
 4     conn=MySQLdb.connect(host=localhost,user=root,passwd=root,port=3306,charset=‘utf8‘)
 5     cur=conn.cursor()
 6      
 7     conn.select_db(python)
 8  
 9     count=cur.execute(select * from test)
10     print there has %s rows record % count
11  
12     result=cur.fetchone()
13     print result
14     print ID: %s info %s % result
15  
16     results=cur.fetchmany(5)
17     for r in results:
18         print r
19  
20     print ==*10
21     cur.scroll(0,mode=absolute)
22  
23     results=cur.fetchall()
24     for r in results:
25         print r[1]
26      
27  
28     conn.commit()
29     cur.close()
30     conn.close()
31  
32 except MySQLdb.Error,e:
33      print "Mysql Error %d: %s" % (e.args[0], e.args[1])

 

python操作MySQL数据库

标签:

人气教程排行