Ubuntu中python链接本地数据库

由于python链接数据库需要下载DB API模块:例如你需要访问Mysql数据,你需要MySQL数据库模块。

DB-API是一个规范。 以便为不同的底层数据库系统和数据库接口程序提供一致的访问接口。

Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同的方式操作各数据库。

1,在Ubuntu安装MySQL数据库模块需要先安装依赖包,命令如下:

sudo apt-get install libmysqlclient-dev libmysqld-dev python-dev python-setuptools
2,安装完依赖包后安装mysqldb
sudo apt-get install python-mysqldb

然后进行链接测试:

1 import MySQLdb as mdb
2 conn = mdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='test', charset='utf8mb4')#链接数据库
3 cursor = conn.cursor()
4 cursor.execute('select * from customer')#执行sql语句
5 r = cursor.fetchall()
6 print r#打印查询的结果
conn.close()#关闭数据库链接

猜你喜欢

转载自www.cnblogs.com/AIHEN/p/9503401.html