簡體   English   中英

MySQLdb Python-如果不存在則使用CREATE TABLE時仍然出現錯誤

[英]MySQLdb Python - Still getting error when using CREATE TABLE IF NOT EXISTS

我正在使用以下代碼在Python中使用表創建數據庫:

def CreateDatabase():
    global DB_CNX
    global DB_NAME
    cursor = DB_CNX.cursor()
    cursor.execute("""CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET 'utf8'""".format(DB_NAME))
    cursor.execute("""CREATE TABLE IF NOT EXISTS NAMES(NAME VARCHAR(50) PRIMARY KEY NOT NULL)""")
    DB_CNX.close()

但是,即使我使用語法“ IF NOT EXISTS”,我仍然會在控制台中遇到如下錯誤:

 Can't create database 'names'; database exists
  cursor.execute("""CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET 'utf8'""".format(DB_NAME))

在SQLite 3中並沒有發生這種情況。我try:將語法與try:except:一起使用,但結果仍然相同。 如何避免這些錯誤?

MySQL實際上是在發出警告而不是錯誤。

您可以像這樣禁止mysql警告:

import MySQLdb as mdb
from warnings import filterwarnings

filterwarnings('ignore', category = mdb.Warning)

現在,mysql警告將消失。

但是mysql錯誤將照常顯示

了解更多有關警告的信息-

https://docs.python.org/2/library/warnings.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM