连接数据库

本文参见这里,示例如何连接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. python 视频逐帧保存为图片

    import cv2 import os def save_img(): video_path = r'F:\test\video1/' videos = os.listdir(video_path) ...

  2. POJ2187 Beauty Contest (旋转卡壳算法 求直径)

    POJ2187 旋转卡壳算法如图 证明:对于直径AB 必然有某一时刻 A和B同时被卡住 所以旋转卡壳卡住的点集中必然存在直径 而卡壳过程显然是O(n)的 故可在O(n)时间内求出直径 凸包具有良好的性 ...

  3. bzoj4031 [HEOI2015]小Z的房间——矩阵树定理

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4031 矩阵树定理的模板题(第一次的矩阵树定理~): 有点细节,放在注释里了. 代码如下: # ...

  4. Java集合类解析 ***

    collection集合 Map集合 Hashtable和HashMap的区别: Hashtable的方法是同步的,而HashMap的方法不是.HashMap可以将空值作为一个表的条目的key或val ...

  5. 一个单例(Singleton),并说明单例的目的和好处

    单例的目的:保证一个类只有单一的实例,也就是说你无法通过new来创建这个类的一个新实例. 单例的好处:当一个对象在程序内部只能有一个实例的时候,它可以保证我们不会重复创建,而是始终指向同一个对象. S ...

  6. Spark SVM分类器

    package Spark_MLlib import java.util.Properties import org.apache.spark.mllib.regression.LabeledPoin ...

  7. [App Store Connect帮助]四、添加 App 图标、App 预览和屏幕快照(6)设置 App 预览海报帧

    App 预览海报帧仅在 App 状态为可编辑时,才能被编辑. 必要职能:“帐户持有人”职能.“管理”职能.“App 管理”职能或“营销”职能.请参见职能权限. 在首页上,点按“我的 App”,选择您的 ...

  8. jQuery——修改网页字体大小

    HTML: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <lin ...

  9. [转]Linux系统调用--fcntl函数详解

    功能描述:根据文件描述词来操作文件的特性. 文件控制函数          fcntl -- file control头文件: #include <unistd.h> #include & ...

  10. mybatis 关联查询

    1.关联的两个实体类 外部类 parent public class Parent{ private String parentId; private String parentName; priva ...