您的位置:首页 > 编程语言 > Python开发

Python中使用MySQL

2015-11-03 15:32 681 查看
今天学习到了数据库的使用,由于我的mac上之前安装好了XAMPP,所以也就是相当于安装好了MySQL;这里我在命令行里输入:

sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start


开启MySQL服务,XAMPP里面显示了已开启:



后面两个服务与本文无关,可以忽略!

看了教程说“在Mac或Linux上,需要编辑MySQL的配置文件,把数据库默认的编码全部改为UTF-8。MySQL的配置文件默认存放在/etc/my.cnf或者/etc/mysql/my.cnf:”

我找了好久,都没有看到那个文件,后来就想那一定在XAMPP那个软件里面,试了试,最后终于找到了那个文件,原来path是:/Applications/XAMPP/etc/my.cnf ,在里面添加了如下内容:

[client]
default-character-set = utf8

[mysqld]
default-storage-engine = INNODB
character-set-server = utf8
collation-server = utf8_general_ci


修改之前是这样的:



修改之后是:(需要重启XAMPP里面的MySQL服务,不是简单的使用:“mysql -u root -p”重新进入MySQL)



这样就可以正确处理中文了!

后面就是安装MySQL驱动了:mysql-connector-python

QXdeMacBook-Pro:~ qx$ sudo easy_install mysql-connector-python
Searching for mysql-connector-python
Reading https://pypi.python.org/simple/mysql-connector-python/ Best match: mysql-connector-python 2.0.4
Downloading http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.4.zip#md5=3df394d89300db95163f17c843ef49df Processing mysql-connector-python-2.0.4.zip
Writing /tmp/easy_install-VHIorB/mysql-connector-python-2.0.4/setup.cfg
Running mysql-connector-python-2.0.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-VHIorB/mysql-connector-python-2.0.4/egg-dist-tmp-W3Jf9z
zip_safe flag not set; analyzing archive contents...
Adding mysql-connector-python 2.0.4 to easy-install.pth file

Installed /Library/Python/2.7/site-packages/mysql_connector_python-2.0.4-py2.7.egg
Processing dependencies for mysql-connector-python
Finished processing dependencies for mysql-connector-python


后面就开始写测试代码了:

QXdeMacBook-Pro:~ qx$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>conn=mysql.connector.connect(user='root',password='',database='python_test',use_unicode=True)
>>> cursor=conn.cursor()
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
>>> cursor.execute('insert into user (id,name) values (%s,%s)',['1','QinXue'])
>>> cursor.rowcount
1
>>> conn.commit()
>>> cursor.close()
True
>>> cursor=conn.cursor()
>>> cursor.execute('select * from user where id = %s',['1'])
>>> values=cursor.fetchall()
>>> values
[(u'1', u'QinXue')]
>>> cursor.close()
True
>>> conn.close()


以下是需要注意的地方:

cursor.execute(‘select * from user where id = %s’,[‘1’]),这里不能写成cursor.execute(‘select * from user where id = %s’,’1’),也就是说传入的第二个参数应该是个list

conn=mysql.connector.connect(user=’root’,password=”,database=’python_test’,use_unicode=True) ,这里打开的必须是一个存在的数据库,否则会报错!

好了,以上就是今天的全部内容!

最后附上参考链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: