MySQL Connector/Python 接口 (二)
连接数据库
本文参见这里,示例如何连接MySQL 数据库。
import mysql.connector
from mysql.connector import errorcode
# 连接数据库需要的参数
# `use_pure` 表示使用纯Python版本的接口,如果置为False,表示使用C库版本的接口,前提是你已经安装了C库版本的接口。
config = {
'user':'scott',
'password':'tiger',
'host':'127.0.0.1',
'database':'employees',
'raise_on_warnings':True,
'use_pure':False,
}
try:
cnx = mysql.connector.connect(**config)
# do something ...
# ...
#最后关闭连接
cnx.close()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
创建数据库
本文参见这里,所有的DDL语句都是通过 cursor 执行的,下面的例子介绍了如何通过 cursor 创建数据库。
from __future__ import print_function
import mysql.connector
from mysql.connecotr import errorcode
# 数据库名字
DB_NAME = "employees"
# 表格名字,以及表格的创建语句
TABLES = []
TABLES['employees'] = (
"CREATE TABLE `employees` ("
" `emp_no` INT(11) NOT NULL AUTO_INCREMENT,"
" `birth_date` DATE NOT NULL,"
" `first_name` VARCHAR(14) NOT NULL,"
" `last_name` VARCHAR(16) NOT NULL,"
" `gender` ENUM('M', 'F') NOT NULL,"
" `hire_date` DATE NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB"
)
# 定义一个函数,创建数据库并处理创建失败异常的情况
def create_database(cursor):
try:
cursor.execute("CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
exit(1)
################# 主流程 #########################
# 连接数据库
cnx = mysql.connector.connect(user='scott')
# 获得 cursor
cursor = cnx.cursor()
# 开始创建一个数据库
try:
cnx.database = DB_NAME
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
create_database(cursor)
cnx.database = DB_NAME
else:
print(err)
exit(1)
# 创建表格
for name, ddl in TABLES.iteritems():
try:
print("Creating table {}: ".format(name), end=" ")
curosr.execute(dll)
except mysql.connecotr.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")
# 在这里做其他处理
# 最后关闭cursor,cnx
cursor.close()
cnx.close()
MySQL Connector/Python 接口 (二)的更多相关文章
- MySQL Connector/Python 接口 (一)
这里仅介绍 MySQL 官方开发的 Python 接口,参见这里: https://dev.mysql.com/doc/connector-python/en/ Chapter 1 Introduct ...
- MySQL Connector/Python 接口 (三)
本文参见这里. 使用缓冲的 cursor,下例给从2000年加入公司并且还在公司的员工薪水从明天起加15% from __future__ import print_function from dec ...
- Snippet: Fetching results after calling stored procedures using MySQL Connector/Python
https://geert.vanderkelen.org/2014/results-after-procedure-call/ Problem Using MySQL Connector/Pytho ...
- Installing MySQL Connector/Python using pip v1.5
The latest pip versions will fail on you when the packages it needs to install are not hosted on PyP ...
- MySQL Connector/Python 安装、测试
安装Connector/Python: # wget http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-pyth ...
- MySQL:Download Connector/Python
MySQL Connector / Python是用于Python平台和开发的标准化数据库驱动程序. 此外,MySQL Connector / Python 8.0支持使用MySQL Server 8 ...
- python使用mysql的三个模块:mysql.connector、sqlalchemy、MySQLdb
在python中使用mysql其实很简单,只要先安装对应的模块即可,那么对应的模块都有什么?官方也没指定也没提供,pcat就推荐自己遇到的3个模块:mysql.connector.sqlalchemy ...
- mysql.connector操作mysql的blob值
This tutorial shows you how to work with MySQL BLOB data in Python, with examples of updating and re ...
- How to Access MySQL with Python Version 3.4
http://askubuntu.com/questions/630728/how-to-access-mysql-with-python-version-3-4 How to Access MySQ ...
随机推荐
- Java应用程序中的声音播放
声音可以创造意境,触发遐想,当与虚拟图像相结合时,更加可以让整个世界充满幻觉,声音是多媒体技术的基础. 播放声音是Java对多媒体的支持一个重要部分,它支持的声音文件类型主要有: AU - (扩展名为 ...
- java笔记线程方式1优先级
* 我们的线程没有设置优先级,肯定有默认优先级. * 那么,默认优先级是多少呢? * 如何获取线程对象的优先级? * public final int getPriority():返回线程对象的优 ...
- CodeForces 731A Night at the Museum (水题)
题意:给定一个含26个英语字母的转盘,问你要得到目标字符串,至少要转多少次. 析:分别从顺时针和逆时针进行,取最小的即可. #pragma comment(linker, "/STACK:1 ...
- bzoj 1047: [HAOI2007]理想的正方形【单调队列】
没有复杂结构甚至不长但是写起来就很想死的代码类型 原理非常简单,就是用先用单调队列处理出mn1[i][j]表示i行的j到j+k-1列的最小值,mx1[i][j]表示i行的j到j+k-1列的最大值 然后 ...
- [Swift通天遁地]一、超级工具-(9)在地图视图MKMapView中添加支持交互动作的标注图标
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- SpringBoot集成MybatisPlus解决Mapper文件修改后动态刷新的问题
很多人在使用SpringBoot集成Mybatis或者MybatisPlus的时候在查询复杂的情况下会写mapper文件,虽然说MyBatisPlus提供了常用的增删查改,但还是难以应付复杂的查询.关 ...
- 生成 Guid
//生成Guid function getGuidGenerator() { var S4 = function () { return (((1 + Mat ...
- MySQL 四种事务隔离级别详解及对比--转
http://www.jb51.net/article/100183.htm 接的隔离级别.它的语法如下: ? 1 SET [SESSION | GLOBAL] TRANSACTION ISOLATI ...
- redis 配置多个ip 解决方案
因为在 redis 中bind 指定的ip 其实为同一网段或localhost 监听ip,在这里配置 内网其他网段或者外网多个ip 后 重启 redis 是不会成功的, 这边建议使用 折中方案,开通 ...
- 【转】rpm包和源码包安装的区别
转自:https://blog.csdn.net/junjie_6/article/details/59483785 建议在安装线上的生产服务器软件包时都用源码安装,这是因为源码安装可以自行调整编译参 ...