python-MySQL学习笔记-第一章链接到并创建数据库

本文只是该链接的翻译后的简单摘要:http://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

1、链接到数据库并创建数据库(请确认MySQL服务已启动)

import mysql.connector
from mysql.connector import errorcode
# **************create database and get connected with it**********
config = {
    'user': 'root',
    'password': '123456',
    'database': 'testdb',
    'raise_on_warnings': True,
}
# cnx = mysql.connector.connect(**config)
# 返回一个 MySQLConnection object
# # 我们可以通过该对象来操作数据库
# cnx.close()
但一般这样链接可能会出现链接错误,所以可以用一定的异常机制来处理这些错误

# To handle connection errors, use the try statement and catch all errors using the errors.Error exception:
try:
    cnx = mysql.connector.connect(**config)     # ** means the parameter is a  dictionary
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 "Datebase does not exist"
    else:
        print err
else:
    cnx.close()

发布了11 篇原创文章 · 获赞 1 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章