python - 与 mysql 服务器的一般连接

标签 python mysql database

有没有办法建立到 mysql 服务器的一般连接,而不是专门连接到它的任何一个数据库?我找到了以下代码片段。 connect 方法连接到名为 employees 的特定数据库。

import mysql.connector

cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees')

cnx.close()

最佳答案

是的,您可以在不指定数据库名称的情况下建立相同的连接:

cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1')

这与使用以下方式从终端连接是一样的:

mysql -h 127.0.0.1 -u scott -ptiger

注意:127.0.0.1 是您的本地主机。

此外,我通常不会在脚本中存储实际的连接信息。我会做更多类似的事情(如果可以的话):

def CloseConnection(cnxIn, cursorIn):

    cursorIn.close()

    cnxIn.close

    return

user = input('Enter your user name: ')

user = user.strip()

password = getpass.getpass()

host = input('Enter the host name: ')

host = host.strip()

cnx = mysql.connector.connect(user=user, password=password, host=host)

cursor =  cnx.cursor(buffered=True)

cursor.execute ('select VERSION()')

row = cursor.fetchone()

CloseConnection(cnx, cursor)

关于python - 与 mysql 服务器的一般连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536145/

相关文章:

python - 如何编辑 django-machina 论坛模板和样式

python - 如何从 [1,4,256] cuda.FloatTensor 形成 [1,1,256]?

python - 由于 json 字符串化字典键导致数据丢失

php - 如何在 Select SQL 报告查询中返回 time() 值

mysql - 如何在 mysql 中实现该 SQL 查询?

python - Selenium 2.0rc3点击功能太快?

mysql - VB.NET | MySQL : A fatal error encountered during command executation

mysql - 在sql中选择子字符串

MySQL 查询永远执行

mysql - 在 MySQL 5.0 中从转储文件创建数据库