Python将数据库查出来的数据转换成字典包字典
时间: 2023-10-07 19:08:25 浏览: 91
可以使用Python中的字典推导式来将查询出来的数据转换成字典套字典的形式。以下是一个示例代码:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host="localhost", user="root", password="password", database="test")
# 创建游标对象
cursor = db.cursor()
# 查询数据
sql = "SELECT * FROM users"
cursor.execute(sql)
results = cursor.fetchall()
# 将查询结果转换成字典套字典的形式
data = {result[0]: { "name": result[1], "age": result[2] } for result in results}
# 输出转换后的字典
print(data)
# 关闭游标和数据库连接
cursor.close()
db.close()
```
在上述示例代码中,我们首先连接了一个名为`test`的数据库,并查询了`users`表中的所有数据。然后,使用字典推导式将查询结果转换成字典套字典的形式,并将其保存在`data`变量中。最后,我们输出了转换后的字典。
相关问题
python 数据库查询结果转dict,将python sql列表转换为字典
可以使用Python标准库中的`DictCursor`来实现将数据库查询结果转换为字典。下面是一个示例代码,其中假设你已经建立了一个名为`mydatabase`的数据库,并且表名为`mytable`:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 创建游标对象,使用字典形式返回查询结果
mycursor = mydb.cursor(dictionary=True)
# 执行查询语句
mycursor.execute("SELECT * FROM mytable")
# 获取查询结果
result = mycursor.fetchall()
# 打印查询结果
print(result)
```
在`mycursor`对象中使用`dictionary=True`参数可以指定返回的查询结果为字典形式。然后使用`fetchall()`方法可以获取所有的查询结果。每一行数据都会以字典形式返回,其中键为列名,值为对应的列值。
python pandas 将字典数据导入postgresql数据库
以下是两种将字典数据导入PostgreSQL数据库的方法:
1. 使用psycopg2库的copy_from()函数:
```python
import psycopg2
from io import StringIO
import pandas as pd
# 将字典数据转换为DataFrame
data = {'col1': [1, 2, 3], 'col2': ['a', 'b', 'c']}
df = pd.DataFrame(data)
# 将DataFrame转换为字符串
output = StringIO()
df.to_csv(output, sep='\t', index=False, header=False)
output_str = output.getvalue()
# 连接到PostgreSQL数据库
conn = psycopg2.connect(host='***', user='***', password='***', database='***')
cur = conn.cursor()
# 使用copy_from()函数将数据导入数据库
cur.copy_from(StringIO(output_str), table_name)
# 提交更改并关闭连接
conn.commit()
cur.close()
conn.close()
print('done')
```
2. 使用pandas的to_sql()函数:
```python
from sqlalchemy import create_engine
import pandas as pd
# 将字典数据转换为DataFrame
data = {'col1': [1, 2, 3], 'col2': ['a', 'b', 'c']}
df = pd.DataFrame(data)
# 连接到PostgreSQL数据库
engine = create_engine('postgresql://user:password@host:port/database')
# 使用to_sql()函数将数据导入数据库
df.to_sql(table_name, engine, index=False, if_exists='append') # 增量入库
# df.to_sql(table_name, engine, index=False, if_exists='replace') # 覆盖入库
print('done')
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)