默认情况下,MySQLdb包是没有安装的,不信? 看到类似下面的代码你就信了。
-bash-3.2# /usr/local/python2.7.3/bin/python get_cnblogs_news.py Traceback (most recent call last): File "get_cnblogs_news.py", line 9, in <module> import MySQLdb ImportError: No module named MySQLdb 这时我们就不得不安装MySQLdb包了。安装其实也挺简单,具体步骤如下: 1、下载 MySQL for Python 地址:http://sourceforge.net/projects/mysql-python/files/mysql-python/ 我这里安装的是1.2.3版本
wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz 2、解压
tar zxvf MySQL-python-1.2.3.tar.gz 3、安装
$ cd MySQL-python-1.2.3
$ python setup.py build
$ python setup.py install
注:
如果在执行:python setup.py build 遇到以下错误:
EnvironmentError: mysql_config not found
首先查找mysql_config的位置,使用
find / -name mysql_config ,比如我的在/usr/local/mysql/bin/mysql_config
修改setup_posix.py文件,在26行:
mysql_config.path = “mysql_config” 修改为:
mysql_config.path = “/usr/local/mysql/bin/mysql_config”
保存后,然后再次执行:
python setup.py build
python setup.py install
OK,到此大功告成。
python操作mysql数据库
代码语言:javascript复制# 导入MySQL驱动:
>>> import mysql.connector
# 注意把password设为你的root口令:
>>> conn = mysql.connector.connect(user='root', password='password', database='test')
>>> cursor = conn.cursor()
# 创建user表:
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意MySQL的占位符是%s:
>>> cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
>>> cursor.rowcount
1
# 提交事务:
>>> conn.commit()
>>> cursor.close()
# 运行查询:
>>> cursor = conn.cursor()
>>> cursor.execute('select * from user where id = %s', ('1',))
>>> values = cursor.fetchall()
>>> values
[('1', 'Michael')]
# 关闭Cursor和Connection:
>>> cursor.close()
True
>>> conn.close()