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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章