下载好后安装,它会自动检测到计算机Python的安装路径,并自动填写模块解压路径(我的是:D:ProgramFilesActivePython 2.6.6.17Libsite-packages)。
但解压完成后并不能使用,还要修改MySQLdb模块下的一些文件:
①.在MySQLdb目录下(我的是:D:ProgramFilesActivePython 2.6.6.17Libsite-packagesMySQLdb)找到__init__.py:
注释第34、35行的from setsimport ImmutableSet、class DBAPISet(ImmutableSet):,在后面添加class DBAPISet(frozenset):
# from sets import ImmutableSet |
# class DBAPISet(ImmutableSet): |
class DBAPISet(frozenset): |
②.打开converters.py:
注释第37行的from sets import BaseSet, Set,将第45行的return Set([ i for i in s.split(',') ifi ])中的Set改为set;同样将第129行的Set: Set2Str,中的Set改为set(不要修改Set2Str),到这里就修改完毕了
2.建立数据库连接- #encoding=utf-8
- import sys
- import MySQLdb
- reload(sys)
- sys.setdefaultencoding('utf-8')
- db=MySQLdb.connect(user='root',charset='utf8')
注:MySQL的配置文件设置也必须配置成utf8
6.模块功能演示 #!/usr/bin/python import MySQLdb Con= MySQLdb.connect(host='localhost',user='root',passwd='root',db='abc') cursor =con.cursor() sql ="select * from myt" cursor.execute(sql) row=cursor.fetchone() print row cursor.close() con.close() 执行以下SQL语句获取返回值: //获取连接的游标 cursor=conn.cursor() //查询 sql = "select * from 【table】" //新增 sql = "insert into 【table】(字段,字段) values(值,值)" //修改 sql = "update 【table】 set 字段 =‘值’where 条件 " //删除 sql = "delete from 【table】where 条件" cursor.execute(sql) 返回值 cur.execute('select * from tables') 其返回值为SQL语句得到的行数,如:2L,表示2行。 然后,可以从该对象的fetchone或fetchall方法得到行信息。 获取行信息 指针对象的fetchone()方法,是每次得到一行的tuple返回值: 引用 >>> row=cur.fetchone() >>> print row ('user1', '52c69e3a57331081823331c4e69d3f2e', 1000L, 1000L, '/home/FTP/user1','') 指针对象的fetchall()方法,可取出指针结果集中的所有行,返回的结果集一个元组(tuples): 引用 >>> cur.scroll(0,'absolute') >>> row=cur.fetchall() >>> print row (('user1', '52c69e3a57331081823331c4e69d3f2e', 1000L, 1000L, '/home/FTP/user1',''), ('user2', '7e58d63b60197ceb55a1c487989a3720', 1000L, 1000L,'/home/FTP/user2', None)) 移动指针 当使用fetchone()方法是,指针是会发生移动的。所以,若不重置指针,那么使用fetchall的信息将只会包含指针后面的行内容。 手动移动指针使用: cur.scroll(int,parm) 含义为: 引用 int:移动的行数,整数;在相对模式下,正数向下移动,负值表示向上移动。 parm:移动的模式,默认是relative,相对模式;可接受absoulte,绝对模式。 修改数据 修改数据,包括插入、更新、删除。它们都是使用指针对象的execute()方法执行: cur.execute("insert into table (row1, row2) values ('111', '222')") cur.execute("update table set row1 = 'test' where row2 = 'row2' ") cur.execute("delete from table where row1 = 'row1' ") 因单引号“'”用于SQL语句中的标识,所以,python中的字符串需使用双引号括住。 此外,也可以使用python的“格式化字符串”写法,简化命令,例如: cur.execute("update table set row1 = '%s' where row2 = '%s' "%('value1','value2')) ※请注意,'%s'的单引号是SQL语句的间隔符,'value1'的单引号是python的字符串间隔符,其含义是不同的。是否需要间隔符,以及使用双引号还是单引号作为间隔,需根据其含义决定。例如,还有: cur.execute("update FTPUSERS set passwd=%s where userid='%s' "%("md5('123')",'user2')) 这里,paswd=%s是因SQL的md5()函数是不需要单引号间隔的;"md5('123')"是python的字符串中含有单引号,所以用双引号括住。 提交修改 一般情况下,MySQLdb模块会自动提交修改。但我们在更新数据后,手动运行一次: conn.commit() 关闭数据库连接 需要分别的关闭指针对象和连接对象.他们有名字相同的方法 cursor.close() conn.close()