当前位置:编程学习 > python >>

Python MySQLdb模块

 [Python]代码
view source  print ? 01 #-*- encoding: gb2312 -*-

02 import os, sys, string

03 import MySQLdb

04  

05 # 连接数据库 

06 try:

07     conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')

08 except Exception, e:

09     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()


Python代码
    
    
     
      # -*- coding: utf-8 -*-    

     
      #mysqldb   

     
      import time, MySQLdb   

     
        

     
      #连接   

     
      conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8") 

     
      cursor = conn.cursor()   

     
        

     
      #写入   

     
      sql = "insert into user(name,created) values(%s,%s)"  

     
      param = ("aaa",int(time.time()))   

     
      n = cursor.execute(sql,param)   

     
      print n   

     
        

     
      #更新   

     
      sql = "update user set name=%s where id=3"  

     
      param = ("bbb")   

     
      n = cursor.execute(sql,param)   

     
      print n   

     
        

     
      #查询   

     
      n = cursor.execute("select * from user")   

     
      for row in cursor.fetchall():   

     
          for r in row:   

     
              print r   

     
        

     
      #删除   

     
      sql = "delete from user where name=%s"  

     
      param =("aaa")   

     
      n = cursor.execute(sql,param)   

     
      print n   

     
      cursor.close()   

     
        

     
      #关闭   

     
      conn.close()  

    
    
 

基本的使用如上,还是很简单的,进一步使用还没操作,先从网上找点资料放上来,以备后续查看

1.引入MySQLdb库


import MySQLdb

2.和数据库建立连接
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")
提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.

比较常用的参数包括
host:数据库主机名.默认是用本地主机.
user:数据库登陆名.默认是当前用户.
passwd:数据库登陆的秘密.默认为空.
db:要使用的数据库名.没有默认值.
port:MySQL服务使用的TCP端口.默认是3306.
charset:数据库编码.

更多关于参数的信息可以查这里
http://mysql-python.sourceforge.net/MySQLdb.html

然后,这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚

3.执行sql语句和接收返回值
cursor=conn.cursor()
n=cursor.execute(sql,param)
首先,我们用使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.这些方法包括两大类:1.执行命令,2.接收返回值

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条数

补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,