连接数据库

本文参见这里,示例如何连接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 接口 (二)的更多相关文章

  1. MySQL Connector/Python 接口 (一)

    这里仅介绍 MySQL 官方开发的 Python 接口,参见这里: https://dev.mysql.com/doc/connector-python/en/ Chapter 1 Introduct ...

  2. MySQL Connector/Python 接口 (三)

    本文参见这里. 使用缓冲的 cursor,下例给从2000年加入公司并且还在公司的员工薪水从明天起加15% from __future__ import print_function from dec ...

  3. 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 ...

  4. 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 ...

  5. MySQL Connector/Python 安装、测试

         安装Connector/Python: # wget http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-pyth ...

  6. MySQL:Download Connector/Python

    MySQL Connector / Python是用于Python平台和开发的标准化数据库驱动程序. 此外,MySQL Connector / Python 8.0支持使用MySQL Server 8 ...

  7. python使用mysql的三个模块:mysql.connector、sqlalchemy、MySQLdb

    在python中使用mysql其实很简单,只要先安装对应的模块即可,那么对应的模块都有什么?官方也没指定也没提供,pcat就推荐自己遇到的3个模块:mysql.connector.sqlalchemy ...

  8. mysql.connector操作mysql的blob值

    This tutorial shows you how to work with MySQL BLOB data in Python, with examples of updating and re ...

  9. 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 ...

随机推荐

  1. SVN导出指定版本差异文件 ***

    当一个项目进入运营维护阶段以后,不会再频繁地更新全部源文件到服务器,这个时间的修改大多是局部的,因此更新文件只需更新修改过的文件,其他 没有修改过的文件就没有必要上载到服务器.但一个稍微上规模的项目文 ...

  2. JSSDK使用步骤

    绑定域名 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”. 备注:登录后可在“开发者中心”查看对应的接口权限. 引入js文件 在需要调用JS接口的页面引入如下JS文件,( ...

  3. 【WIP_S3】链表

    创建: 2017/12/26 完成: 2018/01/14   [TODO]     S4, S5, S14来处理动态数组   CAF8A81B790F [github 地址]传送门  链表的定义   ...

  4. bzoj 1914: [Usaco2010 OPen]Triangle Counting 数三角形【叉积+极角排序+瞎搞】

    参考:https://blog.csdn.net/u012288458/article/details/50830498 有点神啊 正难则反,考虑计算不符合要求的三角形.具体方法是枚举每个点,把这个点 ...

  5. LOJ#503. 「LibreOJ β Round」ZQC 的课堂(容斥+FHQTreap)

    题面 传送门 题解 首先\(x\)和\(y\)两维互相独立,可以分开考虑,我们以\(x\)为例 我们把\(x\)做个前缀和,那么就是问有多少\(i\)满足\(s_is_{i-1}<0\),其中\ ...

  6. [Qt Creator 快速入门] 第3章 窗口部件

    从这一章开始正式接触Qt的窗口部件.在第2章曾看到 Qt Creator 提供的默认基类只有 QMainWindow.QWidget 和 QDialog 这3种.QMainWindow 是带有菜单栏和 ...

  7. [转]C语言文件操作函数大全(超详细)

    fopen(打开文件)相关函数 open,fclose表头文件 #include<stdio.h>定义函数 FILE * fopen(const char * path,const cha ...

  8. cloudera-server启动File not found : /usr/sbin/cmf-server解决办法(图文详解)

    解决方法 见 cloudera-agent启动File not found : /usr/sbin/cmf-agent解决办法(图文详解) 欢迎大家,加入我的微信公众号:大数据躺过的坑        ...

  9. 图标文件ico制作以及使用说明

    今天说一个图标文件——ico.我们在pc端浏览网页的时候网页栏那块都会显示一个本网站特有的图片,就是我们说的ico了.示例:<link href="image/favicon.ico& ...

  10. Windows提高_2.3第三部分:内核区同步

    第三部分:内核区同步 等待函数(WaitForObject) 等待函数的形式 单个:WaitForSingleObject 多个:WaitForMultipleObjects 一个可以被等待的对象通常 ...