【问题标题】:general connection to a mysql server与 mysql 服务器的一般连接
【发布时间】:2015-05-29 17:58:05
【问题描述】:

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

import mysql.connector

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

cnx.close()

【问题讨论】:

    标签: python mysql database


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多