《MySQL入门很简单》学习笔记(23)之Python访问MySQL数据库(关键词:数据库/MySQL/Python)

来源:互联网 发布:h5仿淘宝下拉加载详情 编辑:程序博客网 时间:2024/04/29 18:25

这本书并没有这一章,我自己学习和做笔记需要,查看各种资料,拼凑的这么一章。

    Python连接MySQL数据库;    Python操纵MySQL数据库;    Python备份MySQL数据库;    Python还原MySQL数据库。

安装MySQL

Linux操作系统下安装MySQL,参见:
《MySQL入门很简单》学习笔记(2)之第3章Linux平台下安装与配置MySQL。
Windows操作系统下安装MySQL,详见书中。

安装MySQL驱动

    由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。

目前,有两个MySQL驱动:

    mysql-connector-python:是MySQL官方的纯Python驱动;    MySQL-python:是封装了MySQL C驱动的Python驱动。

可以把两个都装上,使用的时候再决定用哪个:

    $ pip install mysql-connector==2.1.4        ```    $ sudo easy_install MySQL-python        本条命令在执行时,在我的乌班图上会报错:        ```        _mysql.c:29:20: fatal error: Python.h: No such file or directory        #include "Python.h"        ```        解决办法:            sudo apt-get install python-dev        说明:            我用的是Python2.x,使用Python3的朋友,可以使用命令:                sudo apt-get install python3-dev

Python连接MySQL数据库

# 导入MySQL驱动:>>> import mysql.connector# 注意把password设为你的root口令:>>> conn = mysql.connector.connect(user='root', password='password', database='test', use_unicode=True)>>> 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.rowcount1# 提交事务:>>> conn.commit()>>> cursor.close()# 运行查询:>>> cursor = conn.cursor()>>> cursor.execute('select * from user where id = %s', ('1',))>>> values = cursor.fetchall()>>> values[(u'1', u'Michael')]# 关闭Cursor和Connection:>>> cursor.close()True>>> conn.close()

Python操纵MySQL数据库

Python备份MySQL数据库

Python还原MySQL数据库

参考文献:
1.《MySQL入门很简单》;
2.《MySQL入门很简单》学习笔记(2)之第3章Linux平台下安装与配置MySQL;
3.使用MySQL;
4.python操作mysql数据库;
5.fatal error: Python.h: No such file or directory;
6.Unable to find Protobuf include directory。

阅读全文
0 0
原创粉丝点击