Python Qgis 连接数据库
时间: 2023-11-19 09:04:38 浏览: 187
在 QGIS 中连接数据库的步骤如下:
1. 打开 QGIS 软件,点击菜单栏中的“数据库”按钮,选择“数据管理器”。
2. 在“数据管理器”窗口中,点击“新建连接”按钮。
3. 在“新建连接”窗口中,选择要连接的数据库类型(如 PostgreSQL、MySQL、Oracle 等),输入连接数据库的信息,包括主机名、端口号、数据库名称、用户名和密码等。
4. 点击“测试连接”按钮,测试连接是否成功。如果连接成功,点击“确定”按钮保存连接信息。
5. 在“数据管理器”窗口中,可以看到已经连接的数据库,可以浏览数据库中的表格和数据。
6. 可以在 QGIS 中使用 SQL 查询语句查询数据库中的数据,也可以将数据库中的数据导入到 QGIS 中进行地图制作和分析。
Python 中连接数据库的步骤如下:
1. 安装相应的数据库驱动程序,如 psycopg2、mysql-connector-python、cx_Oracle 等。
2. 导入相应的数据库驱动程序和其他需要的模块,如下面的例子中导入了 psycopg2 和 pandas 模块。
```python
import psycopg2
import pandas as pd
```
3. 使用相应的函数连接数据库,如下面的例子中使用了 psycopg2.connect() 函数连接 PostgreSQL 数据库。
```python
conn = psycopg2.connect(database="mydb", user="myuser", password="mypassword", host="localhost", port="5432")
```
4. 使用 cursor() 函数创建一个游标对象,使用 execute() 函数执行 SQL 查询语句,如下面的例子中查询了一个表格中的数据。
```python
cur = conn.cursor()
cur.execute("SELECT * FROM mytable")
data = cur.fetchall()
```
5. 可以将查询结果转化为 pandas 数据框对象,方便进行数据处理和可视化。
```python
df = pd.DataFrame(data, columns=["col1", "col2", "col3"])
```
6. 最后关闭游标和数据库连接。
```python
cur.close()
conn.close()
```
阅读全文
相关推荐
















