wxin 发表于 2018-8-13 06:13:55

Python 和 MySql

Python与Mysql  一、安装MySQLdb模块
  使用python连接Mysql的前提,就是需要一个让python连接到Mysql的接口,这就是MySQLdb模块。
  验证是否已经安装了MySQLdb:
  ==========================================================
  d:\usr\local\Python25>python
  Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) onwin32
  Type "help", "copyright", "credits" or "license" for more information.
  >>> import MySQLdb
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ImportError: No module named MySQLdb
  ==========================================================
  如果有类似于上面的"No module named MySQLdb",表明MySQLdb尚未安装或安装的不成功!
  MySQL 版本:5.0.67
  下载地址:http://dev.mysql.com/downloads/mysql/5.0.html#downloads
  下载exe文件并安装
  ==========================================================
  Python 版本:2.5
  下载地址:http://www.python.org/download/releases/2.5.4/
  下载msi文件并安装
  MySQLdb版本: MySQLdb Windows binary for Python 2.5
  下载地址:http://biohackers.net/wikiattach/Python2(2e)5/attachments/MySQL-python.exe-1.2.1_p2.win32-py2.5.exe
  参见:http://forums.mysql.com/read.php?50,129618,140611#msg-140611
  常见问题:
  1.无法定位程序输入点 mysql_server_init 于动态链接库 LIBMYSQL.dll 上。
  ----------------------------------------------------------------------------------------------------
  D:\usr\local\Python25&gt;python
  Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) on win32
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; import MySQLdb
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\usr\local\Python25\Lib\site-packages\MySQLdb\__init__.py", line 19, in <module>
  import _mysql
  ImportError: DLL load failed: 找不到指定的程序。
  ----------------------------------------------------------------------------------------------------
  解决方法:把mysql安装目录的bin\libmySQL.dll文件复制到python安装目录的Lib\site-packages下
  ==========================================================
  Python 版本:2.6
  下载地址:http://www.python.org/download/releases/2.6.1/
  下载msi文件并安装
  MySQLdb版本: MySQL-python-1.2.2.win32-py2.6.exe
  下载地址:http://home.netimperia.com/files/misc/MySQL-python-1.2.2.win32-py2.6.exe
  参见:http://sourceforge.net/forum/forum.php?thread_id=2316047&forum_id=70460
  常见问题:
  1.ImportError: DLL load failed: 找不到指定的模块。
  ----------------------------------------------------------------------------------------------------
  D:\usr\local\Python26&gt;python
  Python 2.6 (r26:66721, Oct2 2008, 11:35:03) on win32
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; import MySQLdb
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\usr\local\Python26\Lib\site-packages\MySQLdb\__init__.py", line 19, in <module>
  import _mysql
  ImportError: DLL load failed: 找不到指定的模块。
  ----------------------------------------------------------------------------------------------------
  解决方法:下载libmmd.dll(附件)和libguide40.dll(附件)两个dll文件并复制System32目录之下
  参见:http://sourceforge.net/forum/message.php?msg_id=5613887
  2.ImportError: DLL load failed: 找不到指定的模块。
  ----------------------------------------------------------------------------------------------------
  D:\usr\local\Python26&gt;python
  Python 2.6 (r26:66721, Oct2 2008, 11:35:03) on win32
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; import MySQLdb
  D:\usr\local\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWarning: the sets module is deprecated
  from sets import ImmutableSet
  ----------------------------------------------------------------------------------------------------
  解决方法:
  1) 在文件中 "__init__", 注释掉:
  from sets import ImmutableSet
  class DBAPISet(ImmutableSet):
  新增:
  class DBAPISet(frozenset)
  2) 在文件中"converters.py", 注释掉from sets import BaseSet, Set 这一句话。
  3) 在文件中"converters.py", 修改 "Set" 成为 "set" ( 只有两个地方需要修改):
  大概 line 48: return Set([ i for i in s.split(',') if i ]) 》》 return set([ i for i in s.split(',') if i ])
  大概 line 128: Set: Set2Str, 》》 set: Set2Str
  参见:http://sourceforge.net/forum/message.php?msg_id=5808948
  二、MySQLdb的使用。
  引入我们需要的包
  import MySQLdb
  1.和数据库建立连接
  conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable")
  提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.
  比较常用的参数包括
  host:数据库主机名.默认是用本地主机.
  user:数据库登陆名.默认是当前用户.
  passwd:数据库登陆的秘密.默认为空.
  db:要使用的数据库名.没有默认值.
  port:MySQL服务使用的TCP端口.默认是3306.
  conn连接有两个重要的方法commit【提交新增和修改】,rollback【撤销新增或修改】
  2.执行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返回值:
  引用
  &gt;&gt;&gt; row=cur.fetchone()
  &gt;&gt;&gt; print row
  ('user1', '52c69e3a57331081823331c4e69d3f2e', 1000L, 1000L, '/home/FTP/user1', '')
  指针对象的fetchall()方法,是得到一组tuple,其内容为由行信息组成的tuple值:
  引用
  &gt;&gt;&gt; cur.scroll(0,'absolute')
  &gt;&gt;&gt; row=cur.fetchall()
  &gt;&gt;&gt; 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("insertinto table (row1, row2) values ('111', '222')")
  cur.execute("updatetable set   row1 = 'test'whererow2 = 'row2' ")
  cur.execute("delete fromtablewhere row1 = 'row1' ")
  因单引号“'”用于SQL语句中的标识,所以,python中的字符串需使用双引号括住。
  此外,也可以使用python的“格式化字符串”写法,简化命令,例如:
  cur.execute("updatetable set   row1 = '%s'whererow2 = '%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()
页: [1]
查看完整版本: Python 和 MySql