zoukankan      html  css  js  c++  java
  • 学python(八) 数据库连接

    mysql,oracle,sqlserver

    目前对oracle做了下实践

    1、oracle包安装

    可以在pycharm中settings->project interpreter中+按钮来检索cx_oracle添加

    可以在网站下载https://pypi.org/project/cx-Oracle/#files 然后通过cmd窗口pip install cx_Oraclexxxxx.whl安装

    注意:python如果是32位的,那就下载win32的,还要与python的版本对应上

    2、撸代码

    数据库连接

    handle = cx_Oracle.connect(self.user, self.pwd, self.db)

    或者

    handle = cx_Oracle.connect('%s/%s@%s:1521/%s' % (self.user, self.pwd, self.ip, self.instance))

    连接成功后获取游标对象

    cursor = handle.cursor()

    接下来就可以传输sql语句了

    cursor.execute('SELECT * FROM h1.SYSTEM WHERE ROWNUM = 1')

    或者

    named_params = {'cust' : '7406', 'market': '1'}
    result = cursor.execute('SELECT * FROM h1.cust_info WHERE CUST=:cust and MARKET=:market', named_params)

    现在数据已经在游标里了,即从磁盘到内存中了,接下来就是从内存中取数据了

    # 取一条
    # data=cursor.fetchone()
    
    # 取指定数量条数
    # many_data=cursor.fetchmany(8)
    # 取所有
    all_data=cursor.fetchall()

    cursor游标中存的数据是单链表结构,fetchone是移一个位置,fetchall就是游标指针移到末端了,就不能再去取数据了。

    用完了要及时释放游标对应的内存数据,即释放空间。

    cursor.close()

    有时候为了减少内存碎片,close函数只是把对应内存数据清空。

    close并不是把游标对象删除,该对象还是存在的。

    要释放数据库连接实例,handle对象销毁就释放了。

    参考资料:

    1、https://www.cnblogs.com/isme-zjh/p/11579432.html

  • 相关阅读:
    强连通 HDU 1827
    强联通 HDU 2767 3836
    强连通 HDU 1269
    网络流 poj 2135
    强联通 poj 2762
    android20-[【转】Android的EditText自动获取焦点并弹出输入法问题]
    windows开发中的一点总结
    android19
    android18
    android17
  • 原文地址:https://www.cnblogs.com/ikel/p/13822492.html
Copyright © 2011-2022 走看看