【问题标题】:Python equivalent of PHP mysql_fetch_arrayPython 等效于 PHP mysql_fetch_array
【发布时间】:2012-07-18 21:53:12
【问题描述】:

我想在 MySQL 中获取一个数组。有人可以告诉我如何使用 MySQLdb 来使用 Python 吗?

例如,这是我想在 Python 中做的:

<?php

  require_once('Config.php'); 

  $q = mysql_query("SELECT * FROM users WHERE firstname = 'namehere'");
  $data = mysql_fetch_array($q);
  echo $data['lastname'];

?>

谢谢。

【问题讨论】:

    标签: python mysql sql mysql-python


    【解决方案1】:

    在python中你有dictionary=True,我在python3中测试过。这将返回与 php 中的关联数组非常相似的目录。 例如。

    import mysql.connector
    cnx = mysql.connector.connect(user='root', password='',host='127.0.0.1',database='test1')
    cursor = cnx.cursor(dictionary=True)
    sql= ("SELECT * FROM `users` WHERE id>0")
    cursor.execute(sql)
    results = cursor.fetchall()
    print(results)
    
    【解决方案2】:

    你可以使用这个(dictionary=True):

    import mysql.connector
    
    db = mysql.connector.connect(user='root', password='',host='127.0.0.1', database='test1')
    
    cursor = db.cursor(dictionary=True)
    cursor.execute("SELECT * FROM table")
    
    for row in cursor:
        print(row['column'])
    

    【讨论】:

      【解决方案3】:
      1. 安装 MySQLdb(适用于 Python 的 MySQL 驱动程序)。输入pip install mysql-python
      2. 阅读Python DB API,这是在 Python 中访问数据库的标准方法。

      然后,试试这个:

      >>> import MySQLdb
      >>> connection = MySQLdb.connect(database='test')
      >>> cursor = connection.cursor()
      >>> cursor.execute('SELECT * FROM users WHERE firstname = %s',('somename',))
      >>> results = cursor.fetchall()
      >>> for i in results:
             print i
      

      【讨论】:

      • 令人担忧的是,这是某种形式的 SQL 转义的唯一答案。
      • 感谢您的帮助!我还有一个问题。当我使用它时,数据以这种格式返回:(('dave',), ('jake',))。我怎样才能编辑这些数据的格式,所以它是这样的('dave','jake')。我正在遍历返回的数据并将每个数据用作变量。出于我的目的,这将更容易操作。再次感谢。
      • names = [i[0] for i in cursor.fetchall()]
      【解决方案4】:

      我会使用SQLAlchemy。像这样的东西可以解决问题:

      engine = create_engine('mysql://username:password@host:port/database') 连接 = engine.connect() result = connection.execute("从用户中选择用户名") 结果中的行: 打印“用户名:”,行['用户名'] 连接.close()

      【讨论】:

        【解决方案5】:

        试试:

        import MySQLdb
        connection = MySQLdb.connect(host="localhost",  # your host
                             user="root",  # username
                             passwd="password",  # password
                             db="frateData")  # name of the database)
        cursor = connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM users WHERE firstname = %s',['namehere'])
        data = cursor.fetchall()
        print data['lastname']
        

        请注意,通过传递以下参数来启动光标:“MySQLdb.cursors.DictCursor” 返回一个列表而不是数组,因此您可以使用它们的键名引用数据,在您的情况下是姓氏。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-07-03
          • 1970-01-01
          • 1970-01-01
          • 2012-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多