zoukankan      html  css  js  c++  java
  • python连接数据库

    驱动安装
    安装MySQL驱动
    由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。MySQL官方提供了mysql-connector-python驱动,但是安装的时候需要给
    支持的版本Python versions v2.6, v2.7 and Python v3.1 to 3.3 (See version overview)
    实现Python DB API 2.0 (PEP 249)。
    纯Python MySQL协议的实现。
    Oracle积极开发和维护。官方维护的库。
    包括Django数据库后端。
    pip命令加上参数--allow-external:
    $ pip install mysql-connector-python --allow-external mysql-connector-python
    如果上面的命令安装失败,可以试试另一个驱动:
    $ pip install mysql-connector
    我们演示如何连接到MySQL服务器的test数据库:
    # 导入MySQL驱动: >>> import mysql.connector # 注意把password设为你的root口令: >>> conn = mysql.connector.connect(user='root', password='password', database='test') >>> cursor = conn.cursor() # 创建user表: >>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') # 插入一行记录,注意MySQL的占位符是%s: >>> cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
    # 删除表。
    cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") >>> cursor.rowcount 1 # 提交事务: >>> conn.commit() >>> cursor.close() # 运行查询: >>> cursor = conn.cursor() >>> cursor.execute('select * from user where id = %s', ('1',)) >>> values = cursor.fetchall() >>> values [('1', 'Michael')] # 关闭Cursor和Connection: >>> cursor.close() True >>> conn.close()
    由于Python的DB-API定义都是通用的,所以,操作MySQL的数据库代码和SQLite类似。
    小结
    • 执行INSERT等操作后要调用commit()提交事务;
    • MySQL的SQL占位符是%s。
     
     
    使用Python的DB-API时,只要搞清楚Connection和Cursor对象,打开后一定记得关闭,就可以放心地使用。
    使用Cursor对象执行insert,update,delete语句时,执行结果由rowcount返回影响的行数,就可以拿到执行结果。
    使用Cursor对象执行select语句时,通过featchall()可以拿到结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录。
    如果SQL语句带有参数,那么需要把参数按照位置传递给execute()方法,有几个?占位符就必须对应几个参数,例如:
    cursor.execute('select * from user where name=? and pwd=?', ('abc', 'password'))
    SQLite支持常见的标准SQL语句以及几种常见的数据类型。具体文档请参阅SQLite官方网站。
     
    注意:
    在Python中操作数据库时,要先导入数据库对应的驱动,然后,通过Connection对象和Cursor对象操作数据。
    要确保打开的Connection对象和Cursor对象都正确地被关闭,否则,资源就会泄露。
    如何才能确保出错的情况下也关闭掉Connection对象和Cursor对象呢?请回忆try:...except:...finally:...的用法。
     
    PyMySQL
    URL
    Python versions
    2.4 - 3.2
     
  • 相关阅读:
    Hive 2.1.1安装配置
    vi / vim 删除以及其它命令
    『MySQL』时间戳转换
    update 中实现子查询
    hive lateral view 与 explode详解
    xpath定位方法详解
    Python int与string之间的转化
    ORM、SQLAchemy
    python bottle 简介
    python wsgi 简介
  • 原文地址:https://www.cnblogs.com/TomBombadil/p/10969284.html
Copyright © 2011-2022 走看看