MySQLdb是Python连接MySQL的模块,下面介绍一下源码方式安装MySQLdb:

  1. 首先要下载下载:请到官方网站http://sourceforge.net/projects/mysql-python/或者点击链接下载http://downloads.sourceforge.net/project/mysql-python/mysql-python-test/1.2.3c1/MySQL-python-1.2.3c1.tar.gz?use_mirror=nchc

  2. 解压:tar zxvf MySQL-python*

  3. 进入文件目录,运行以下命令:
    python setup.py install

  4. 安装完成,到你的python安装目录下的site-packages目录里检查以下文件是否存在,如果存在即代表安装成功了
    Linux:MySQL_python-1.2.3c1-py2.6-linux-i686.egg
    Mac OS X:MySQL_python-1.2.3c1-py2.6-macosx-10.4-x86_64.egg
    注:如果碰到mysql_config not found的问题,有两种方法解决:
    1)ln -s /usr/local/mysql/bin/mysql_config /usr/local/bin/mysql_config
    将mysql_confi从你的安装目录链接到/usr/local/bin目录下,这样就可以在任意目录下访问了(也可以放到/usr/bin)
    2)编辑源码文件夹的site.cfg文件,去掉#mysql_config = /usr/local/bin/mysql_config前的注释#,修改后面的路径为你的mysql_config真正的目录就可以了。(如果不知道mysql_config在哪里,运行命令:whereis mysql_config)

注:如果碰到import error: libmysqlclient.so.18: cannot open shared object file: No such file or directory

解决方法: locate or find libmysqlclient.so.18

link path/libmysqlclient.so.18 /usr/lib/libmysqlclient.so.18

vi /etc/ld.so.conf    //加入libmysqlclient.so.18 所在的目录

插入: /usr/lib/

保存退出后执行/sbin/ldconfig生效

  1. 测试方法
    1)运行命令python进入python运行环境
    2)输入以下python代码进行测试
    import MySQLdb

  2. test=MySQLdb.connect(db='mydb',host='myhost',user='u',passwd='p')

  3. cur = test.cursor()

  4. cur.execute('show databases;')

  5. for data in cur.fetchall():

  6. print data

  7. 3)如果你在屏幕上看到了你几个数据库的库名的输出代表你安装成功了

  8. 可能碰到的问题
    1)问题:ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
    原因是python无法找到mysql目录下的libmysqlclient_r.so.16动态库,其实MySQLdb是调用mysql的c函数库.所以本机上首先得安装了mysql
    然后: export LD_LIBRARY_PATH=/usr/local/mysql/lib/mysql:$LD_LIBRARY_PATH
    并且将/usr/local/mysql5.1/lib/mysql 放入/etc/ld.so.conf中
    /etc/ld.so.conf改后内容为:
    include ld.so.conf.d/*.conf
    /usr/local/mysql5.1/lib/mysql
    最后重新再测试一下,就不会有上面的问题了

MySQLdb操作:

Python代码

  1. #!/usr/bin/env python

  2. #coding=utf-8

  3. ###################################

  4. #MySQLdb 示例

  5. #

  6. ##################################

  7. import MySQLdb

  8. #建立和数据库系统的连接

  9. conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')

  10. #获取操作游标

  11. cursor = conn.cursor()

  12. #执行SQL,创建一个数据库.

  13. cursor.execute("""create database python """)

  14. #关闭连接,释放资源

  15. cursor.close();

#!/usr/bin/env python

#coding=utf-8

##################################

#MySQLdb 示例 #

##################################

import MySQLdb

#建立和数据库系统的连接

conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')

#获取操作游标

cursor = conn.cursor()

#执行SQL,创建一个数据库.

cursor.execute("""create database python """)

#关闭连接,释放资源

cursor.close();

创建数据库,创建表,插入数据,插入多条数据

Python代码:

  1. #!/usr/bin/env python

  2. #coding=utf-8

  3. ###################################

  4. #MySQLdb 示例

  5. #

  6. ##################################

  7. import MySQLdb

  8. #建立和数据库系统的连接

  9. conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')

  10. #获取操作游标

  11. cursor = conn.cursor()

  12. #执行SQL,创建一个数据库.

  13. cursor.execute("""create database if not exists python""")

  14. #选择数据库

  15. conn.select_db('python');

  16. #执行SQL,创建一个数据表.

  17. cursor.execute("""create table test(id int, info varchar(100)) """)

  18. value = [1,"inserted ?"];

  19. #插入一条记录

  20. cursor.execute("insert into test values(%s,%s)",value);

  21. values=[]

  22. #生成插入参数值

  23. for i in range(20):

  24. values.append((i,'Hello mysqldb, I am recoder ' + str(i)))

  25. #插入多条记录

  26. cursor.executemany("""insert into test values(%s,%s) """,values);

  27. #关闭连接,释放资源

  28. cursor.close();

#!/usr/bin/env python

#coding=utf-8

###################################

#MySQLdb 示例 #

##################################

import MySQLdb

#建立和数据库系统的连接

conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')

#获取操作游标

cursor = conn.cursor()

#执行SQL,创建一个数据库.

cursor.execute("""create database if not exists python""")

#选择数据库

conn.select_db('python');

#执行SQL,创建一个数据表.

cursor.execute("""create table test(id int, info varchar(100)) """)

value = [1,"inserted ?"];

#插入一条记录

cursor.execute("insert into test values(%s,%s)",value);

values=[]

#生成插入参数值

for i in range(20):

values.append((i,'Hello mysqldb, I am recoder ' + str(i)));

#插入多条记录

cursor.executemany("""insert into test values(%s,%s) """,values);

#关闭连接,释放资源

cursor.close();

查询和插入的流程差不多,只是多了一个得到查询结果的步骤

Python代码:

  1. #!/usr/bin/env python

  2. #coding=utf-8

  3. #

  4. # MySQLdb 查询

  5. #

  6. #######################################

  7. import MySQLdb

  8. conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')

  9. cursor = conn.cursor()

  10. count = cursor.execute('select * from test')

  11. print '总共有 %s 条记录',count

  12. #获取一条记录,每条记录做为一个元组返回

  13. print "只获取一条记录:"

  14. result = cursor.fetchone();

  15. print result

  16. #print 'ID: %s info: %s' % (result[0],result[1])

  17. print 'ID: %s info: %s' % result

  18. #获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录

  19. print "只获取5条记录:"

  20. results = cursor.fetchmany(5)

  21. for r in results:

  22. print r

  23. print "获取所有结果:"

  24. #重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,

  25. cursor.scroll(0,mode='absolute')

  26. #获取所有结果

  27. results = cursor.fetchall()

  28. for r in results:

  29. print r

  30. conn.close()

默认mysqldb返回的是元组,这样对使用者不太友好,也不利于维护
下面是解决方法

  1. import MySQLdb

  2. import MySQLdb.cursors

  3. conn = MySQLdb.Connect (

  4. host = 'localhost', user = 'root' ,

  5. passwd = '', db = 'test', compress = 1,

  6. cursorclass = MySQLdb.cursors.DictCursor, charset='utf8') // <- important

  7. cursor = conn.cursor()

  8. cursor.execute ("SELECT name, txt FROM table")

  9. rows = cursor.fetchall()

  10. cursor.close()

  11. conn.close()

  12. for row in rows:

  13. print row ['name'], row ['txt'] # bingo!

    1. # another (even better) way is:

    2. conn = MySQLdb . Connect (

    3. host = ' localhost ', user = 'root' ,

    4. passwd = '', db = 'test' , compress = 1)

    5. cursor = conn.cursor (cursorclass = MySQLdb.cursors.DictCursor)

    6. # ...

    7. # results by field name

    8. cursor = conn.cursor()

    9. # ...

    10. # ...results by field number

python MySQLdb安装和使用的更多相关文章

  1. PYTHON -MYSQLDB安装遇到的问题和解决办法

    目前下载的mysqldb在window下没有exe安装包了,只有源码. 使用python setup.py install 命令安装, 报错如下: 异常信息如下: F:\devtools\MySQL- ...

  2. windows python MySQLdb 安装配置

    一.环境 系统:windows10/7/8 软件: 1.python2.7.XX(https://www.python.org/downloads/或者https://www.python.org/f ...

  3. Python MySQLdb在Linux下的快速安装

    在家里windows环境下搞了一次 见   python MySQLdb在windows环境下的快速安装.问题解决方式 http://blog.csdn.NET/wklken/article/deta ...

  4. cygwin 下安装python MySQLdb

    cygwin 下安装python MySQLdb 1) cygwin 更新 运行 cygwin/setup-x86_64.exe a 输入mysql,选择下面的包安装: libmysqlclient- ...

  5. Python 3安装MySQLdb

    Python 2安装的是mysql-python,Python 3安装mysql-python以后,仍然不能import MySQLdb,原来Python 3应该安装mysqlclient,就可以im ...

  6. python MySQLdb在windows环境下的快速安装

    python MySQLdb在windows环境下的快速安装.问题解决方式 使用python访问mysql,需要一系列安装 linux下MySQLdb安装见 Python MySQLdb在Linux下 ...

  7. windows 环境下安装python MySQLdb

    使用Python访问MySQL,需要一系列安装 Linux下MySQLdb安装见 Python MySQLdb在Linux下的快速安装 http://blog.csdn.NET/wklken/arti ...

  8. 117、python MySQLdb在windows环境下的快速安装、问题解决方式

    使用Python访问MySQL,需要一系列安装 Linux下MySQLdb安装见 Python MySQLdb在Linux下的快速安装 http://blog.csdn.NET/wklken/arti ...

  9. python MySQLdb Windows下安装教程及问题解决方法(python2.7)

    使用python访问mysql,需要一系列安装 linux下MySQLdb安装见  Python MySQLdb在Linux下的快速安装http://www.jb51.net/article/6574 ...

随机推荐

  1. 【转】不要去SeaWorld

    不要去SeaWorld 很多人喜欢海洋动物,比如海豚和“杀人鲸”(orca),但是我建议不要去海洋世界看它们.海豚和杀人鲸都是有灵性的,跟人类的智慧很接近,而且对人极其友好的动物.“杀人鲸”名字吓人, ...

  2. Proxy源代码分析——谈谈如何学习Linux网络编程

    Linux是一个可靠性非常高的操作系统,但是所有用过Linux的朋友都会感觉到, Linux和Windows这样的"傻瓜"操作系统(这里丝毫没有贬低Windows的意思,相反这应该 ...

  3. [转]Servlet 单例多线程

    Servlet如何处理多个请求访问? Servlet容器默认是采用单实例多线程的方式处理多个请求的: 1.当web服务器启动的时候(或客户端发送请求到服务器时),Servlet就被加载并实例化(只存在 ...

  4. SNF.Net 快速开发平台Spring.Net.Framework 诞生的由来与规划

    没有快速开发平台的时候只能感慨自己曾经浪费了那么多精力在拖拽控件上,总写重复的代码,却花了很多精力且不能体现自己的价值.SNF快速开发平台能把你解放出来,让你有更多的时间参与到核心业务逻辑中去,让你有 ...

  5. 更新django到2.x

    django-2.x 已经发布了.想体验一下它的新功能.于是把之前电脑上的django-1.11.7uninstall 掉 一.卸载django-1.11.7: pip3 uninstall djan ...

  6. ubuntu 安装python mysqldb

    sudo apt-get install python-mysqldb #!/usr/bin/python #-*-coding:utf-8-*- ''' This file include all ...

  7. 《Java Concurrency》读书笔记,Java并发编程实践基础

    1. 基本概念 程序,是一组有序的静态指令,是一种静态的概念.程序的封闭性是指程序一旦运行,其结果就只取决于程序本身:程序的再现性是指当机器在同一数据集上重复执行同一程序时,机器内部的动作系列完全相同 ...

  8. mysql获得60天前unix时间示例

    在mysql中获取多少天前的unix时间的方法.首先根据now()获得当前时间,使用adddate()方法获得60天前时间,使用unix_timestamp()方法转换时间类型 select UNIX ...

  9. Net AOP(五) 各种IoC框架下实现AOP

    public interface IUserProcessor { void RegUser(User user); } public class UserProcessor : IUserProce ...

  10. 菜鸟学SSH(三)——Struts2国际化自动检测浏览器语言版

    前几天发了一篇Struts国际化的博客——<菜鸟学习SSH(二)——Struts2国际化手动切换版>,有网友提了一个意见,见下图: 于是就有了下面修改的版本: web.xml <?x ...