pythonMySQLdb如何配置python链接MYSQL

这篇文章给大家介绍python MySQLdb如何配置python链接MYSQL,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

创新互联公司企业建站,10年网站建设经验,专注于网站建设技术,精于网页设计,有多年建站和网站代运营经验,设计师为客户打造网络企业风格,提供周到的建站售前咨询和贴心的售后服务。对于网站建设、成都做网站中不同领域进行深入了解和探索,创新互联在网站建设中充分了解客户行业的需求,以灵动的思维在网页中充分展现,通过对客户行业精准市场调研,为客户提供的解决方案。

1、下载 MySQL for Python
wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz

2、安装
yum install python-devel-2.7.5-48.el7.x86_64
tar zxvf MySQL-python-1.2.3.tar.gz
$ cd MySQL-python-1.2.3

修改setup_posix.py中mysql_config.path = “mysql_config” 修改为你mysql软件下对应路径 
mysql_config.path = "/home/mysql/soft/mysql5717/bin/mysql_config"
 
$ python setup.py build
$ python setup.py install

[root@node1 lib]# python testconn.py 
Traceback (most recent call last):
  File "testconn.py", line 3, in
    import MySQLdb    
  File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 19, in
  File "build/bdist.linux-x86_64/egg/_mysql.py", line 7, in
  File "build/bdist.linux-x86_64/egg/_mysql.py", line 6, in __bootstrap__
ImportError: libmysqlclient.so.20: cannot open shared object file: No such file or directory
[root@node1 lib]# find / -name libmysqlclient
[root@node1 lib]# find / -name libmysqlclient.so.20
/home/mysql/soft/mysql5717/lib/libmysqlclient.so.20

做一个软连接到/usr/lib64 目录(64为系统)
 ln -s /home/mysql/soft/mysql5717/lib/libmysqlclient.so.20  /usr/lib64/libmysqlclient.so.20

还是有报错找不到socket

[root@node1 duanfj]# python testconn.py 
Traceback (most recent call last):
  File "testconn.py", line 6, in
    conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",port=3306,charset="utf8")  
  File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 81, in Connect
  File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 187, in __init__
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")

这个简单  做个软链接  大功告成
ln -s /tmp/my3306.sock /tmp/mysql.sock

[root@node1 MySQL-python-1.2.3]# python testconn.py 
1
1
row1
2
row2
3
row
4
row4
[root@node1 MySQL-python-1.2.3]# 
##############
[root@node1 MySQL-python-1.2.3]# cat testconn.py 
# -*- coding: utf-8 -*-     
#mysqldb    
import MySQLdb    
   
#连接    
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",port=3306,charset="utf8")  
cursor = conn.cursor()    
   
#写入    
sql = "insert into test(a,b) values(%s,%s)"   
param = (4,"row4")    
n = cursor.execute(sql,param)    
print n    

#查询    
n = cursor.execute("select * from test")    
for row in cursor.fetchall():    
    for r in row:    
        print r    
   
#删除    

#关闭    
conn.close()  

关于python MySQLdb如何配置python链接MYSQL就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前文章:pythonMySQLdb如何配置python链接MYSQL
网站URL:http://pwwzsj.com/article/gecips.html