python连接lightdb(一)

使用python连接lightdb,主要分为两种情况:
一、通过第三方包连接
二、通过Django等web框架连接
本文主要介绍通过第三方包连接(psycopg2)
安装
pip install psycopg2

import psycopg2


def connect():
    conn = None
    try:
        # 创建连接
        conn = psycopg2.connect(database="postgres", user="lightdb", password="lightdb123", host='10.20.149.228',
                                port=5678)
        # conn = psycopg2.connect("host=10.20.149.228 port=45678 dbname=postgres user=lightdb password=lightdb123")
        print('connnect')
        # 创建游标
        cur = conn.cursor()
        # 执行sql
        cur.execute('select * from t1;')
        # 获取结果
        db_version = cur.fetchall()
        print(db_version)
        # 关闭游标
        cur.close()
    except (Exception) as error:
        print(error)
    finally:
        if conn is not None:
            # 关闭连接
            conn.close()
            print('Database connection closed.')


if __name__ == '__main__':
    connect()

主要方法
connect() 创建连接
cursor() 创建游标
execute() 执行sql
fetchall() 获取所有结果,返回列表
fetchone() 获取一行结果(非表中的一行记录)

posted @ 2022-06-17 17:51  起司24  阅读(49)  评论(0编辑  收藏  举报