连接数据库

本文参见这里,示例如何连接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. CMake使用总结

    总结CMake的常用命令,并介绍有用的CMake资源. CMake意为cross-platform make,可用于管理c/c++工程.CMake解析配置文件CMakeLists.txt生成Makef ...

  2. Face alignment at 3000FPS via Regressing Local Binrary features 理解

    这篇是Ren Shaoqing发表在cvpr2014上的paper,论文是在CPR框架下做的,想了解CPR的同学可以参见我之前的博客,网上有同学给出了code,该code部分实现了LBF,链接为htt ...

  3. KeepAlived的介绍

    KeepAlived介绍 keepalived keepalived是一个类似于layer3, 4 & 7交换机制的软件,也就是我们平时说的第3层.第4层和第7层交换. Keepalived的 ...

  4. Feature分支(转载)

    转自:http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/00137602623300 ...

  5. Hadoop回收站及fs.trash参数详解

    前言: Linux系统里,个人觉得最大的不方便之一就是没有回收站的概念.rm -rf很容易造成极大的损失.而在Hadoop或者说HDFS里面,有trash(回收站)的概念,可以使得数据被误删以后,还可 ...

  6. 【原创】Maven安装和配置

    ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 前提 利用maven进行java项目或J2EE项目开发,要求电脑已配置java开发环境(JDK) 下载 下载地址:http://maven.a ...

  7. JavaScript--DOM方法

    getElementsByName()方法 返回带有指定名称的节点对象的集合. 语法: document.getElementsByName(name) 与getElementById() 方法不同的 ...

  8. Windows8.1进入IIS管理器的方法

    以前在本机的Windows8.1操作系统中安装了IIS,很久没有使用过,今天在安装IBM Http Server的时候启动失败,才想起来IIS占用了80端口,需要把IIS服务停止掉.找了半天才找到进入 ...

  9. java https客户端请求

    String pathname = Test3.class.getResource("/client.jks").getFile(); System.out.println(pat ...

  10. Python学习日记之中文支持

    解决中文输出错误 在开头添加 # -*- coding: utf-8 -*- 即可