zoukankan      html  css  js  c++  java
  • Python学习--17 访问数据库

    实际开发中,我们会经常用到数据库。

    Python里对数据库的操作API都很统一。

    SQLite

    SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。

    Python内置了sqlite3。

    #coding:utf-8
    import sqlite3
    
    conn = sqlite3.connect('test.db')
    cursor = conn.cursor()
    
    # sqlite创建表时,若id为INTEGER类型且为主键,可以自动递增,在插入数据时id填NULL即可
    # cursor.execute('create table user(id integer primary key, name varchar(25))') #执行一次
    
    # 插入一条数据
    cursor.execute('insert into user(id,name)values(NULL,"yjc")')
    
    # 返回影响的行数
    print(cursor.rowcount)
    
    #提交事务,否则上述SQL不会提交执行
    conn.commit()
    
    # 执行查询
    cursor.execute('select * from user')
    
    # 获取查询结果
    print(cursor.fetchall())
    
    # 关闭游标和连接
    cursor.close()
    conn.close()
    

    输出:

    1
    [(1, 'yjc'), (2, 'yjc')]
    

    我们发现Python里封装的数据库操作很简单:
    1、获取连接conn
    2、获取游标cursor
    3、使用cursor.execute()执行SQL语句;
    4、使用cursor.rowcount返回执行insert,update,delete语句受影响的行数;
    5、使用cursor.fetchall()获取查询的结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录;
    6、关闭游标和连接。

    如果SQL语句带有参数,那么需要把参数按照位置传递给cursor.execute()方法,有几个?占位符就必须对应几个参数,示例:

    cursor.execute('select * from user where name=? ', ['abc'])
    

    为了能在出错的情况下也关闭掉Connection对象和Cursor对象,建议实际项目里使用try:...except:...finally:...结构。

    MySQL

    MySQL是最流行的关系数据库。

    SQLite的特点是轻量级、可嵌入,但不能承受高并发访问,适合桌面和移动应用。而MySQL是为服务器端设计的数据库,能承受高并发访问,同时占用的内存也远远大于SQLite。

    使用需要先安装MySQL:https://dev.mysql.com/downloads/mysql/

    Windows版本安装时注意选择UTF-8编码,以便正确地处理中文。

    MySQL的配置文件是my.ini,Linux一般位于/etc/my.cnf。配置里需要设置编码为utf-8。配置示例:

    [client]
    default-character-set = utf8
    
    [mysqld]
    default-storage-engine = INNODB
    character-set-server = utf8
    collation-server = utf8_general_ci
    

    Python并未内置MySQL的驱动。需要先安装:

    $ pip3 install mysql-connector
    
    Collecting mysql-connector
      Downloading mysql-connector-2.1.4.zip (355kB)
        100% |████████████████████████████████| 358kB 355kB/s
    Building wheels for collected packages: mysql-connector
      Running setup.py bdist_wheel for mysql-connector ... done
    Successfully built mysql-connector
    Installing collected packages: mysql-connector
    Successfully installed mysql-connector-2.1.4
    

    Python使用MySQL示例:

    # coding: utf-8
    import mysql.connector
    
    conn = mysql.connector.connect(user='root', password='123456', database='test')
    
    cursor = conn.cursor()
    
    cursor.execute("insert into user(id,name,age)values(null,'python', 20)")
    print(cursor.rowcount)
    conn.commit()
    
    cursor.execute("select * from user order by id desc limit 3")
    print(cursor.fetchall())
    
    cursor.close()
    conn.close
    
    

    输出:

    1
    [(25, 'python', 1, 20, 1), (24, 'python', 1, 20, 1), (23, 't2', 2, 23, 1)]
    

    如果SQL语句带有参数,那么需要把参数按照位置传递给cursor.execute()方法,MySQL的占位符是%s,示例:

    cursor.execute('select * from user where name=%s and age=%s', ['python', 20])
    

    由于Python的DB-API定义都是通用的,所以,操作MySQL的数据库代码和SQLite类似。

  • 相关阅读:
    查询,创建,扩充表空间&&impdp--------表空间大全
    TOJ3660家庭关系(并查集+hash+图的连通性)
    [置顶] iptables 性能 测试
    CSU1312:榜单(模拟)
    uvalive 2326
    TOJ 2732存钱计划(三)(单源最短路)
    CSU1315:全场最水题之陈兴老师与比赛
    【图像处理】最临近插值和双线性内插值算法实现比较
    poj 3090 Visible Lattice Points 法利系列||通过计
    美丽的谎言(王愿共勉)
  • 原文地址:https://www.cnblogs.com/52fhy/p/6380344.html
Copyright © 2011-2022 走看看