TA的每日心情 | 开心 2023-8-9 11:05 |
---|
|
1.客户端安装psycopg2
- C:\Users\zhyu>pip install psycopg2
- Collecting psycopg2
- Using cached psycopg2-2.8.5-cp38-cp38-win_amd64.whl (1.1 MB)
- Installing collected packages: psycopg2
- Successfully installed psycopg2-2.8.5
复制代码 2.服务端启动postgresql
- [postgres@vm1 ~]$ pg_ctl start
- waiting for server to start....2020-05-31 07:40:41.254 CST [2025] LOG: starting PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
- 2020-05-31 07:40:41.254 CST [2025] LOG: listening on IPv4 address "0.0.0.0", port 5432
- 2020-05-31 07:40:41.254 CST [2025] LOG: listening on IPv6 address "::", port 5432
- 2020-05-31 07:40:41.332 CST [2025] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"
- 2020-05-31 07:40:41.517 CST [2025] LOG: redirecting log output to logging collector process
- 2020-05-31 07:40:41.517 CST [2025] HINT: Future log output will appear in directory "/app/postgres/12/data".
- done
- server started
复制代码 3.进入python环境
- Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
- Type "help", "copyright", "credits" or "license" for more information.
- >>>
复制代码 4.加载psycopg2
5.建立连接符
- conn=psycopg2.connect(database="postgres",user="postgres",password="postgres",host="192.168.56.101",port="5432")
复制代码 6.建立游标
7.执行sql
- cursor.execute("select version()")
复制代码 8.获取结果
- >>> results=cursor.fetchall()
- >>> print(results)
- [('PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit',)]
复制代码 9.关闭游标
10.关闭连接
整体流程步骤:
- Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
- Type "help", "copyright", "credits" or "license" for more information.
- >>> import psycopg2
- >>> conn=psycopg2.connect(database="postgres",user="postgres",password="postgres",host="192.168.56.101",port="5432")
- >>> cursor=conn.cursor()
- >>> cursor.execute("select version()")
- >>> results=cursor.fetchall()
- >>> print(results)
- [('PostgreSQL 12.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit',)]
- >>> cursor.close()
- >>> conn.close()
- >>>
复制代码
|
|