【问题标题】:using flags in Python MySQLdb在 Python MySQLdb 中使用标志
【发布时间】:2014-01-09 00:46:29
【问题描述】:

我想使用 python MySQLdb 访问带有 --local-infile 标志的远程 MySQL 服务器,以便能够从本地文件加载数据。 (正如这个问题中提到的Importing CSV to MySQL table returns an error #1148

我用

db = MySQLdb.connect(host="127.0.0.1", port=3307, user="someuser", passwd="password", db="sql_db")

创建数据库连接。如何使用 MySQLdb 模仿mysql -u username -p dbname --local-infile

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:

    我知道这对于最初的问题来说已经晚了,但如果有人来这里寻找同样的问题,你可以这样做:

    import mysql.connector
    
    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="",
        allow_local_infile=True,
    )
    

    您可以在此处查看文档以获取其他标志:https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html

    如果你想将它设置为数据库配置而不是连接,你可以这样做:

    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="",
    )
    
    mycursor = mydb.cursor()
    
    try:
        command = "SET GLOBAL local_infile = 'ON';"
        mycursor.execute(command)
    except mysql.connector.errors.DatabaseError:
        pass
    

    【讨论】:

      【解决方案2】:

      您可以将您的数据库配置放入本地文件,然后在使用时读取。

      config.ini

      [MySQL]
      host=192.168.20.28
      user=root
      password=123456
      db_name=ovp_global
      charset=utf8
      

      py 代码:

      import MySQLdb
      import ConfigParser
      
      config = ConfigParser.ConfigParser()
      config.readfp(open("config.ini", "r"))
      
      
      def get_connection():
          host = config.get('MySQL', 'host')
          user = config.get('MySQL', 'user')
          passwd = config.get('MySQL', 'password')
          db = config.get('MySQL', 'db_name')
          charset = config.get('MySQL', 'charset')
      
          return MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, charset=charset)
      

      【讨论】:

      • MySQLdb.connect() 是否支持标志?我可以在配置中设置 local-infile=1 并将其传入吗?
      猜你喜欢
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 2014-01-09
      • 2018-06-05
      • 2011-09-21
      • 1970-01-01
      • 2014-09-15
      相关资源
      最近更新 更多