Python操纵MySQL.

  1. import MySQLdb  
  2.   
  3. #建立和数据库系统的连接  
  4. conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
  5.   
  6. #获取操作游标  
  7. cursor = conn.cursor()  
  8. #执行SQL,创建一个数据库.  
  9. cursor.execute("""create database python """)  
  10.   
  11. #关闭连接,释放资源  
  12. cursor.close();  

 

 

 

 

  1. import MySQLdb  
  2.   
  3. conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')  
  4.   
  5. cursor = conn.cursor()  
  6.   
  7. count = cursor.execute('select * from test')  
  8.   
  9. print '总共有 %s 条记录',count  
  10.   
  11. #获取一条记录,每条记录做为一个元组返回  
  12. print "只获取一条记录:"  
  13. result = cursor.fetchone();  
  14. print result  
  15. #print 'ID: %s   info: %s' % (result[0],result[1])  
  16. print 'ID: %s   info: %s' % result   
  17.   
  18. #获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录  
  19. print "只获取5条记录:"  
  20. results = cursor.fetchmany(5)  
  21. for r in results:  
  22.     print r  
  23.   
  24. print "获取所有结果:"  
  25. #重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,  
  26. cursor.scroll(0,mode='absolute')  
  27. #获取所有结果  
  28. results = cursor.fetchall()  
  29. for r in results:  
  30.     print r  
  31. conn.close()  

 

 

 

 

 

 

 

  1. import MySQLdb  
  2.   
  3. #建立和数据库系统的连接  
  4. conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
  5.   
  6. #获取操作游标  
  7. cursor = conn.cursor()  
  8. #执行SQL,创建一个数据库.  
  9. cursor.execute("""create database if not exists python""")  
  10.   
  11. #选择数据库  
  12. conn.select_db('python');  
  13. #执行SQL,创建一个数据表.  
  14. cursor.execute("""create table test(id int, info varchar(100)) """)  
  15.   
  16. value = [1,"inserted ?"];  
  17.   
  18. #插入一条记录  
  19. cursor.execute("insert into test values(%s,%s)",value);  
  20.   
  21. values=[]  
  22.   
  23.   
  24. #生成插入参数值  
  25. for i in range(20):  
  26.     values.append((i,'Hello mysqldb, I am recoder ' + str(i)))  
  27. #插入多条记录  
  28.   
  29. cursor.executemany("""insert into test values(%s,%s) """,values);
  30. cursor.commit()
  31. #关闭连接,释放资源  
  32. cursor.close();  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值