程序示例
===========


您可前往电科金仓官网下载 `Python测试用例 <https://kingbase.oss-cn-beijing.aliyuncs.com/KES_INTERFACE/testyongli/python/python.zip>`_ 。

连接数据库
---------------

.. code:: PROGRAMLISTING

   import ksycopg2

   database = "TEST"
   user = "SYSTEM"
   password = "123456"
   host = "127.0.0.1"
   port = "54321"

   if __name__ == "__main__":
       try:
           conn = ksycopg2.connect("dbname={} user={} password={} host={} port={}"
                                   .format(database, user, password, host, port))

       except Exception, e:
           print(e)
           print("Fail")
       else:
           print("Success")

		   
获取结果集
---------------

.. code:: PROGRAMLISTING

   import ksycopg2

   database = "TEST"
   user = "SYSTEM"
   password = "123456"
   host = "127.0.0.1"
   port = "54321"

   if __name__ == "__main__":
       try:
           conn = ksycopg2.connect("dbname={} user={} password={} host={} port={}"
                                   .format(database, user, password, host, port))

           cur = conn.cursor()

           cur.execute('drop table if exists test_ksy')
           cur.execute('create table test_ksy(id integer, name TEXT)')

           cur.execute("insert into test_ksy values(%s, %s)", (1, "John"))
           cur.execute("insert into test_ksy values(%s, %s)", (2, '中文测试文字'))
           cur.execute("insert into test_ksy values(%s, %s)", (3, '！@#￥%……'))

           conn.commit()

           cur.execute("select * from test_ksy")
           rows = cur.fetchall()
           for row in rows:
               print(cell)

           cur.close()
           conn.commit()
           conn.close()

       except Exception, e:
           print(e)
           print("Fail")
       else:
           print("Success")


存储过程
--------------------------

.. code:: PROGRAMLISTING
    
    /*创建存储过程*/
    CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS $$
    BEGIN
         OPEN $1 FOR SELECT col FROM test;
         RETURN $1;
    END;
    $$ LANGUAGE plsql；


.. code:: PROGRAMLISTING

    /*调用示例*/
    curl = conn.cursor()
    curl.callproc('reffunc', ['curname'])

    cur2 = conn.cursor('curname')
    for record in cur2:
       print(record)
       pass


连接池
---------------

.. code:: PROGRAMLISTING

    import threading

    import ksycopg2
    from ksycopg2 import pool

    # 配置数据库连接参数
    DB_HOST = '127.0.0.1'
    DB_NAME = 'TEST'
    DB_USER = 'SYSTEM'
    DB_PASSWORD = '123456'
    DB_PORT = "54321"

    # 配置连接池参数
    MIN_CONN = 1
    MAX_CONN = 5

    def simple_test():
        # 创建连接池
        connection_pool = ksycopg2.pool.SimpleConnectionPool(MIN_CONN, MAX_CONN,
                                                            user=DB_USER,
                                                            password=DB_PASSWORD,
                                                            host=DB_HOST,
                                                            port=DB_PORT,
                                                            database=DB_NAME)

        # 从连接池获取连接
        connection = connection_pool.getconn()

        # 创建游标
        cursor = connection.cursor()

        cursor.execute("drop table if exists test_user")
        cursor.execute("create table test_user (id int, name varchar(20))")

        # 插入数据
        cursor.execute("INSERT INTO test_user VALUES (%s, %s)", (1, "xxx"))
        # 提交事务
        connection.commit()
        # 执行查询
        cursor.execute("SELECT * FROM test_user")
        # 获取结果
        rows = cursor.fetchall()

        # 打印结果
        for row in rows:
            print(row)

        # 关闭游标
        cursor.close()
        # 将连接放回连接池
        connection_pool.putconn(connection)
        # 关闭所有连接
        connection_pool.closeall()

    # 定义一个函数来执行数据库插入和查询操作
    def db_operation(connection_pool, i):
        # 从连接池获取连接
        connection = connection_pool.getconn()
        # 创建游标
        cursor = connection.cursor()
        # 插入数据
        cursor.execute("INSERT INTO test_user VALUES (%s, %s)", (i, threading.current_thread().name))
        # 提交事务
        connection.commit()
        # 执行查询
        cursor.execute("SELECT * FROM test_user")
        # 获取结果
        rows = cursor.fetchall()
        print(threading.current_thread().name)
        # 打印结果
        for row in rows:
            print(row)
        # 关闭游标
        cursor.close()
        # 将连接放回连接池
        connection_pool.putconn(connection)

    def thread_test():
        # 创建连接池
        connection_pool = ksycopg2.pool.ThreadedConnectionPool(MIN_CONN, MAX_CONN,
                                                            user=DB_USER,
                                                            password=DB_PASSWORD,
                                                            host=DB_HOST,
                                                            port=DB_PORT,
                                                            database=DB_NAME)

        # 创建多个线程来执行数据库操作
        threads = []
        for i in range(1,5):
            thread = threading.Thread(target=db_operation,args=(connection_pool, i))
            threads.append(thread)
            thread.start()

        # 等待所有线程执行完毕
        for thread in threads:
            thread.join()

        # 关闭所有连接
        connection_pool.closeall()

    if __name__ == "__main__":
        print("simple:")
        simple_test()
        print("thread:")
        thread_test()


COPY
----

.. code:: PROGRAMLISTING

    # -*- coding: utf-8 -*-
    import ksycopg2

    database = "TEST"
    user = "SYSTEM"
    password = "123456"
    host = "127.0.0.1"
    port = "54321"


    def connect_ksycopg2():
        try:
            conn = ksycopg2.connect(
                "dbname={} user={} password={} host={} port={}".format(database, user, password, host, port))
        except Exception as e:
            print(e)
            return None
        else:
            return conn

            
    def copy_from():
        conn = connect_ksycopg2()
        if conn is not None:
            cur = conn.cursor()
            try:
                f = open("in.csv")
                # 将本地文件内的数据复制到room表的id和name列，本地文件以逗号分隔
                cur.copy_from(f, 'room', columns=("id", "name"), sep=',')
                conn.commit()
            except Exception as e:
                print(e)

            cur.close()
            conn.close()
        else:
            return None


    def copy_to():
        conn = connect_ksycopg2()
        if conn is not None:
            cur = conn.cursor()
            try:
                f = open("out.csv", "w")
                # 将room表的id和name列写入到本地，本地文件以逗号分隔
                cur.copy_to(f, 'room', columns=("id", "name"), sep=',')
                conn.commit()
            except Exception as e:
                print(e)

            cur.close()
            conn.close()
        else:
            return None

            
    def copy_expert():
        conn = connect_ksycopg2()
        if conn is not None:
            copy_sql = "COPY room(id, name) TO STDOUT WITH CSV HEADER DELIMITER as ','"
            cur = conn.cursor()
            try:
                f = open("test_expert.csv", "w")
                # 执行COPY命令，将room表的id和name列写入到本地，本地文件以逗号分隔
                cur.copy_expert(sql=copy_sql, file=f)
                conn.commit()
            except Exception as e:
                print(e)

            cur.close()
            conn.close()
        else:
            return None


    if __name__ == "__main__":
        copy_from()
        copy_to()
        copy_expert()


大对象
------

.. code:: PROGRAMLISTING

    # -*- coding: utf-8 -*-
    import ksycopg2

    database = "TEST"
    user = "SYSTEM"
    password = "123456"
    host = "127.0.0.1"
    port = "54321"

    conn = ksycopg2.connect(database=database, user=user, password=password, host=host, port=port)

    if conn is not None:
        cur = conn.cursor()

        cur.execute('drop table if exists test_lob')
        cur.execute('create table test_lob(id integer, b BLOB, c CLOB, ba bytea)')

        ba = bytearray("中文测试字符bytearray", "UTF8")
        b = bytes('中文测试字符bytes' * 2, "UTF8")
        u = u'中文字unicode' * 3
        s = '中文str' * 4

        cur.execute("insert into test_lob values(%s, %s, %s, %s)", (1, ba, ba, ba))
        cur.execute("insert into test_lob values(%s, %s, %s, %s)", (2, b, b, b))
        cur.execute("insert into test_lob values(%s, %s, %s, %s)", (3, u, u, u))
        cur.execute("insert into test_lob values(%s, %s, %s, %s)", (4, s, s, s))

        cur.execute("select * from test_lob")
        rows = cur.fetchall()

        for row in rows:
            for cell in row:
                if isinstance(cell, memoryview):
                    print(type(cell), cell[:].tobytes().decode('UTF8'), " ", end="")
                else:
                    print(type(cell), cell, " ", end="")
            print()

        cur.close()
        conn.commit()
        conn.close()