Python MySQLdb模块

[代码] [Python]代码

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代码
     
  1. # -*- coding: utf-8 -*-     
  2. #mysqldb    
  3. import time, MySQLdb    
  4.    
  5. #链接    
  6. conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")  
  7. cursor = conn.cursor()    
  8.    
  9. #写入    
  10. sql = "insert into user(name,created) values(%s,%s)"   
  11. param = ("aaa",int(time.time()))    
  12. n = cursor.execute(sql,param)    
  13. print n    
  14.    
  15. #更新    
  16. sql = "update user set name=%s where id=3"   
  17. param = ("bbb")    
  18. n = cursor.execute(sql,param)    
  19. print n    
  20.    
  21. #查询    
  22. n = cursor.execute("select * from user")    
  23. for row in cursor.fetchall():    
  24.     for r in row:    
  25.         print r    
  26.    
  27. #删除    
  28. sql = "delete from user where name=%s"   
  29. param =("aaa")    
  30. n = cursor.execute(sql,param)    
  31. print n    
  32. cursor.close()    
  33.    
  34. #关闭    
  35. conn.close()   

 

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

1.引入MySQLdb库 python

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:数据库编码.
mysql

更多关于参数的信息能够查这里 
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条数据. 
fetchone(self):返回一条结果行. 
scroll(self, value, mode='relative'):移动指针到某一行.若是mode='relative',则表示从当前所在行移动value条,若是mode='absolute',则表示从结果集的第一行移动value条. 

下面的代码是一个完整的例子. 
#使用sql语句,这里要接收的参数都用%s占位符.要注意的是,不管你要插入的数据是什么类型,占位符永远都要用%s 
sql="insert into cdinfo values(%s,%s,%s,%s,%s)" 
#param应该为tuple或者list 
param=(title,singer,imgurl,url,alpha) 
#执行,若是成功,n的值为1 
n=cursor.execute(sql,param) 

#再来执行一个查询的操做 
cursor.execute("select * from cdinfo") 
#咱们使用了fetchall这个方法.这样,cds里保存的将会是查询返回的所有结果.每条结果都是一个tuple类型的数据,这些tuple组成了一个tuple 
cds=cursor.fetchall() 
#由于是tuple,因此能够这样使用结果集 
print cds[0][3] 
#或者直接显示出来,看看结果集的真实样子 
print cds 

#若是须要批量的插入数据,就这样作 
sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)" 
#每一个值的集合为一个tuple,整个参数集组成一个tuple,或者list 
param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2)) 
#使用executemany方法来批量的插入数据.这真是一个很酷的方法! 
n=cursor.executemany(sql,param) 

4.关闭数据库链接 
须要分别的关闭指针对象和链接对象.他们有名字相同的方法 
cursor.close() 
conn.close() 

四步完成,基本的数据库操做就是这样了.下面是两个有用的链接 
MySQLdb用户指南: 
http://mysql-python.sourceforge.net/MySQLdb.html 
MySQLdb文档: 
http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.htmlsql

5 编码(防止乱码)数据库

须要注意的点:app

    1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
    2 MySQL
数据库charset=utf-8 
    3 Python
链接MySQL是加上参数 charset=utf8 
    4 
设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)fetch

    
  1. #encoding=utf-8 
  2.  import sys 
  3.  import MySQLdb 
  4.   
  5.  reload(sys) 
  6.  sys.setdefaultencoding('utf-8'
  7.   
  8.  db=MySQLdb.connect(user='root',charset='utf8'

注:MySQL的配置文件设置也必须配置成utf8

设置 MySQL  my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(一般在/etc/mysql/my.cnf) 
编码

[client] default-character-set = utf8 [mysqld] default-character-set = utf8
相关文章
相关标签/搜索