对Python操作方法说明


Mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。Python操作数据库需要安装一个第三方的模块。

由于Python的数据库模块有专门的数据库模块的规范,所以,其实不管使用哪种数据库的方法都大同小异的,这里就给出一段示范的Python操作代码:

  1. #-*- encoding: gb2312 -*-  
  2. import os, sys, string  
  3. import MySQLdb  
  4.  
  5. # 连接数据库   
  6. try:  
  7.     conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')  
  8. except Exception, e:  
  9.     print e  
  10.     sys.exit()  
  11.  
  12. # 获取cursor对象来进行操作  
  13.  
  14. cursor = conn.cursor()  
  15. # 创建表  
  16. sql = "create table if not exists test1(name varchar(128) primary key, age int(4))" 
  17. cursor.execute(sql)  
  18. # 插入数据  
  19. sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)  
  20. try:  
  21.     cursor.execute(sql)  
  22. except Exception, e:  
  23.     print e  
  24.  
  25. sql = "insert into test1(name, age) values ('%s', %d)" % ("张三", 21)  
  26. try:  
  27.     cursor.execute(sql)  
  28. except Exception, e:  
  29.     print e  
  30. # 插入多条  
  31.  
  32. sql = "insert into test1(name, age) values (%s, %s)"   
  33. val = (("李四", 24), ("王五", 25), ("洪六", 26))  
  34. try:  
  35.     cursor.executemany(sql, val)  
  36. except Exception, e:  
  37.     print e  
  38.  
  39. #查询出数据  
  40. sql = "select * from test1" 
  41. cursor.execute(sql)  
  42. alldata = cursor.fetchall()  
  43. # 如果有数据返回,就循环输出, alldata是有个二维的列表  
  44. if alldata:  
  45.     for rec in alldata:  
  46.         print rec[0], rec[1]  
  47.  
  48.  
  49. cursor.close()  
  50.  
  51. conn.close() 
  1. 如何使Python嵌入C++应用程序?
  2. 深入探讨Ruby与Python语法比较
  3. Python学习资料介绍分享
  4. Python学习经验谈:版本、IDE选择及编码解决方案
  5. 浅析Python的GIL和线程安全

相关内容

    暂无相关文章

评论关闭