python - 使用 Python mysql 连接器将 Mysql 列名称存储在数组中

标签 python mysql arrays mysql-connector-python

在操作数据库本身方面,我对 mysql 还很陌生。我成功地将新行存储在表中,但我的下一次尝试会稍微复杂一些。

我想从现有的 mysql 数据库中获取列名并将它们保存到 python 数组中。我正在使用官方的 mysql 连接器。

我想我可以通过 information_schema.columns 命令实现这一点,但我不知道如何构建查询并将信息存储在数组中。它将大约有 100-200 列,因此性能可能会成为一个问题,所以我认为对每一列重复我的方式是不明智的。

使用连接器将代码注入(inject) mysql 的基本代码是:

def insert(data):
    query = "INSERT INTO templog(data) " \
        "VALUES(%s,%s,%s,%s,%s)"
    args = (data)

try:
    db_config = read_db_config()
    conn = MySQLConnection(db_config)

    cursor = conn.cursor()
    cursor.execute(query, args)

    #if cursor.lastrowid:
     #   print('last insert id', cursor.lastrowid)
    #else:
     #   print('last insert id not found')

    conn.commit()

    cursor.close()
    conn.close()
except Error as error:
    print(error)

如前所述,需要修改以上代码才能从 sql server 获取数据。提前致谢!

最佳答案

感谢您的帮助!

得到这个作为工作代码:

def GetNames(web_data, counter):
#get all names from the database
connection = create_engine('mysql+pymysql://user:pwd@server:3306/db').connect()
result = connection.execute('select * from price_usd')
a = 0
sql_matrix = [0 for x in range(counter + 1)]
for v in result:
    while a == 0:
        for column, value in v.items():
            a = a + 1
            if a > 1: 
                sql_matrix[a] = str(('{0}'.format(column)))

这将从现有的 sql 数据库中获取所有列名

关于python - 使用 Python mysql 连接器将 Mysql 列名称存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47962043/

相关文章:

python - 使用 Python 在 Maya 中调整图像大小

mysql - 基于行计算滚动总和

php - 查询没有获得所有值

arrays - 在给定某些条件的情况下,为数组元素赋值

python - 这是使用 Python 3 unittest 测试 stdout 的正确方法吗?

python - Python 和 Django 常量的最佳实践

python 3 time.sleep() "serial read"

MySQL 查询按特定类别列出多类别文章,同时仍检索主猫

c# - 使用 Npgsql 在 postgresql 中插入字符数组

java - 如何打印四列数据