登录
首页 >  数据库 >  MySQL

python MySQLdb 配置 python链接MYSQL

来源:SegmentFault

时间:2023-02-24 08:58:04 437浏览 收藏

大家好,今天本人给大家带来文章《python MySQLdb 配置 python链接MYSQL》,文中内容主要涉及到MySQL、python,如果你对数据库方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

1、下载 MySQL for Python
wget

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 "testcon import n.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》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于数据库的相关知识,请关注golang学习网公众号!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表