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 ...
随机推荐
- codemirror插件-文件比较组件merge
目的: 为了实现文件比较功能 引用文件 从github下载项目后,从以下路径引用文件,其中部分github分支中codemirror.js 需要运行项目,自动合成 <link rel=style ...
- E20170606-hm
pipeline n. 管道; 输油管道; 渠道,传递途径; dump vt. 倾倒; 倾销; 丢下,卸下; 摆脱,扔弃; n. 垃圾场; 仓库; 无秩序地累积;
- bzoj 1791: [Ioi2008]Island 岛屿【基环树+单调队列优化dp】
我太菜了居然调了一上午-- 这个题就是要求基环树森林的基环树直径和 大概步骤就是找环->dp找每个环点最远能到达距离作为点权->复制一倍环,单调队列dp 找环是可以拓扑的,但是利用性质有更 ...
- 【React Native】React Native项目设计与知识点分享
闲暇之余,写了一个React Native的demo,可以作为大家的入门学习参考. GitHub:https://github.com/xujianfu/ElmApp.git GitHub:https ...
- random模块思维导图
- [LOJ#10132]异象石
Description Adera 是 Microsoft 应用商店中的一款解谜游戏. 异象石是进入 Adera 中异时空的引导物,在 Adera 的异时空中有一张地图.这张地图上 有 N 个点,有 ...
- 【洛谷3239_BZOJ4008】[HNOI2015] 亚瑟王(期望 DP)
题目: 洛谷 3239 分析: 卡牌造成的伤害是互相独立的,所以 \(ans=\sum f_i\cdot d_i\) ,其中 \(f_i\) 表示第 \(i\) 张牌 在整局游戏中 发动技能的概率.那 ...
- ACM_抢糖果
抢糖果 Time Limit: 2000/1000ms (Java/Others) Problem Description: 今天计实班的生活委员心情大好,在永诚超市狂购了好多好多糖果,好开心~o(∩ ...
- 用Movie显示gif(1)SimpleGif
代码如下: import android.content.Context; import android.graphics.Canvas; import android.graphics.Movie; ...
- Snipaste强大离线/在线截屏软件的下载、安装和使用
步骤一: https://zh.snipaste.com/ ,去此官网下载. 步骤二:由于此是个绿色软件,直接解压即可. 步骤三:使用,见官网.ttps://zh.snipaste.com 按F1 ...