簡體   English   中英

使用 python 創建 Mysql 數據庫 - 不斷收到 1064 錯誤(...在 '%s' 附近使用正確的語法)

[英]Creating Mysql database with python - keep getting 1064 error (… right syntax to use near '%s' )

事情是這樣的:我正在嘗試通過導入數據庫的名稱然后創建它來創建一個新的 MySQL 數據庫。

這是代碼:

import mysql.connector as mcon

# DB Connect
stdb = mcon.connect(
    host        = "localhost",
    user        = "root",
    password    = "pass",
    database    = "trffc_int_data")
cursor = stdb.cursor()

# Creating new DB
NewDB = input(" Enter the Database name : ")
sqlsynt = "CREATE DATABASE IF NOT EXISTS %s"
cursor.execute(sqlsynt,NewDB)                 
cursor.commit()
print ("New database created!") 

看起來不錯,但我不斷收到錯誤“1065 >>您的 SQL 語法有錯誤;請查看與您的 MySQL 服務器版本相對應的手冊,了解在 '%s' <<”附近使用的正確語法

它指出了這條線: cursor.execute(sqlsynt,NewDB)

可能是什么問題呢?

您不能像這樣綁定 object 名稱(在本例中為數據庫名稱),只能綁定值。 您將不得不求助於字符串格式。 例如:

newDB = input(" Enter the Database name : ")
sqlsynt = f"CREATE DATABASE IF NOT EXISTS {newDB}"
cursor.execute(sqlsynt,NewDB)

暫無
暫無

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

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