pyodbc 接口

1.环境

centos7 + x86_64

4.5.8.5

python3

2.安装pyodbc

yum install -y gcc gcc-c++ unixODBC-devel
python3 -m pip install pyodbc

3.配置odbc

修改配置文件cd /opt/highgo/hgdb-see-4.5.8/etc/drivers/ODBC/unixODBC/etc,在odbcinst.ini中添加以下内容:

Text
[HighGoDriver]
Description=HGDB driver for Linux
Driver=/opt/highgo/hgdb-see-4.5.8/etc/drivers/ODBC/psqlODBC/lib/psqlodbcw.so
Setup=/opt/highgo/hgdb-see-4.5.8/etc/drivers/ODBC/psqlODBC/lib/psqlodbcw.so
UsageCount=1

配置环境变量export ODBCSYSINI=/opt/highgo/hgdb-see-4.5.8/etc/drivers/ODBC/unixODBC/etc

4.编写demo

# -*-coding:utf-8-*-
import pyodbc
import datetime

#在Python中,str表示字符串类型。一般用单引号、双引号和三引号来表示字符串,表示字符串的单引号和双引号应该成对出现。
#print(pyodbc.drivers())

try:
#方式一:使用自定义的DSN
# conn = pyodbc.connect('DSN=HighGoOdbc;PWD=test')
# 方式二:使用驱动
conn = pyodbc.connect('DRIVER={PostgreSQL Unicode(x64)};SERVER=192.168.168.159;port=5866;DATABASE=newnew;UID=sysdba;PWD=Hello@123')
cursor = conn.cursor()
#cursor.execute("select '数据库版本:['||version()||']'")
#result = cursor.fetchall()
#print(result)

#查询数据
cursor.execute("select count(*) as student_count from student")
row = cursor.fetchone()
print("目前已有: " + str(row.student_count) + "条数据")

#查询数据
cursor.execute("select * from student")
rows = cursor.fetchall()
print("查询到:" + str(rows.__len__()) + "条数据")
for row in rows:
print(row.id, row.name)

#关闭Cursor对象
cursor.close()
#关闭连接
conn.close()

except Exception as e:
print(e)