【问题标题】:Checking if database connected to Python检查数据库是否连接到 Python
【发布时间】:2020-02-08 10:23:53
【问题描述】:

我尝试使用mysql.connector.connect() 连接到 数据库,我检查了传递给函数的所有参数是否正常并且它们是正常的。我希望此代码的输出确认与数据库的连接。我在PyCharm 中运行它,没有任何反应,只是在等待一些事情...... MySQL 工作台已全部设置好,我的意思是连接已经过测试并且运行良好。

import mysql.connector

db = mysql.connector.connect(host="localhost", user="root", password="Asdf124#")
if (db):
    print("connected")
else:
    print("fail")

【问题讨论】:

  • this 回答你的问题了吗?

标签: mysql python mysql python-3.x database connection


【解决方案1】:

来自文档中的示例:

import mysql.connector
from mysql.connector import errorcode

try:
  cnx = mysql.connector.connect(user='scott',
                                database='employ')
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)
else:
  cnx.close()

这是连接数据库时处理异常的正确方法。

【讨论】:

    猜你喜欢
    • 2019-08-10
    • 2012-08-26
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多