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

- 连接数据库_
- 获取结果集_
- 存储过程_

您可前往人大金仓官网下载 `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