• Python数据库访问之SQLite3、Mysql


    现有的数据库管理系统有很多种,本文选择介绍两种DBMS:SQLite 3 和 Mysql。

    SQLite 3

    SQLite 3是Python 3预装的、相当完备、无需配置的基于SQL的数据库管理系统。要使用SQLite,只需导入sqlite3库,并使用Python标准化数据库API来编程,而不用处理其他工作,比如:安装数据库、配置等等。

    Python数据库API 提供了一种标准机制,可以针各种各样的数据库管理系统,包括SQLite。不管使用什么后台数据库,代码所遵循的过程都是一样的:连接 -> 创建游标 -> 交互(利用游标,使用SQL管理数据)->提交/回滚 ->关闭

    示例1:

    #导入你需要的库
    import sqlite3
    #1、建立与数据库的连接
    connection=sqlite3.connect('test.db');
    #2、创建数据游标
    cursor=connection.cursor()
    #3、执行一些SQL操作
    cursor.execute("""select date('NOW')""")
    print(cursor.fetchone())
    #4、提交所做的修改,使修改永久保留
    connection.commit()
    #5、完成时关闭链接
    connection.close()

    输出:

    ('2013-06-26',)

    示例2:

    创建数据库 -> 插入数据 -> 查询

    import sqlite3
    
    db='test.sqlite'    #数据库名
    drop_table_sql="drop table if exists books;"
    create_table_sql="""
    create table books(
        id integer primary key autoincrement unique not null,
        name text not null,
        price integer,
        publish_date date not null
    );
    """
    
    connection=sqlite3.connect(db)
    cursor=connection.cursor()
    
    #创建数据库
    cursor.execute(drop_table_sql)
    cursor.execute(create_table_sql)
    
    #插入数据
    insert_sql="insert into books (name,price,publish_date) values (?,?,?)"# ? 为占位符
    cursor.execute(insert_sql,('java',123.23,'2012-12-03'))
    cursor.execute(insert_sql,('C++',83.23,'2013-02-03'))
    connection.commit()
    
    #查询
    select_sql = "SELECT * FROM books"
    cursor.execute(select_sql)
    #返回一个list,list中的对象类型为tuple(元组)
    data=cursor.fetchall()
    for t in data:
        print(t)
    
    connection.close()

    输出:

    (1, 'java', 123.23, '2012-12-03')
    (2, 'C++', 83.23, '2013-02-03')

    Mysql

    Mysql是非常流行的开源关系性数据库。

    要使用Python访问Mysql,需要一个连接库,即对Python DB API的一个实现,相当于JAVA中的MySQL的JDBC Driver。其中比较著名就是MySQLdb(Django项目使用它),不过,目前MySQLdb并不支持python3.x。我们只能采用其他连接库,MySQL官方已经提供了MySQL连接器,而且已经有支持Python3.x的版本了。

    MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python DB API version 2.0
    关于MySQL Connector/Python的各种介绍、安装、API等文档,请参考官网:http://dev.mysql.com/doc/connector-python/en/index.html

    示例:

     
    import mysql.connector
    import sys, os
     
    user = 'root'
    pwd  = '123456'
    host = '127.0.0.1'
    db   = 'test'
    
    connection = mysql.connector.connect(user=user, password=pwd, host=host, database=db)
    cursor = connection.cursor()
    
    #创建数据库表
    drop_table_sql="drop table if exists person;"
    create_table_sql = """
    CREATE TABLE person(
        id int(10) AUTO_INCREMENT PRIMARY KEY,
        name varchar(20),
        age int(4) 
    )CHARACTER SET utf8;
    """
    try:
        cursor.execute(drop_table_sql)
        cursor.execute(create_table_sql)
    except mysql.connector.Error as err:
        print("create table 'mytable' failed.")
        print("Error: {}".format(err.msg))
        sys.exit()
    
    #插入数据
    insert_sql = 'INSERT INTO person(name, age) VALUES (%s,%s)'
    try:
        cursor.execute(insert_sql,('Jay', 22))
        cursor.execute(insert_sql,('Tony', 26))
        cursor.execute(insert_sql,('',24))
    except mysql.connector.Error as err:
        print("insert table 'mytable' failed.")
        print("Error: {}".format(err.msg))
        sys.exit()
    
    #查询数据
    select_sql = "SELECT * FROM person"
    try:
        #cursor.execute() 返回 None; 执行SQL后的信息存储在cursor对象内。
        cursor.execute(select_sql)
        #获取一条记录,每条记录做为一个tuple(元组)返回
        data=cursor.fetchone()
        print(data)
        
        #获取2条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的2条记录
        data=cursor.fetchmany(2)
        print(data)
        
        cursor.execute(select_sql)
        #获取所有结果 
        data=cursor.fetchall()
        print(data)
        
        cursor.execute(select_sql)
        #获取所有结果
        for (id, name, age) in cursor:
            print("ID:{}  Name:{}  Age:{}".format(id, name, age))
        
    except mysql.connector.Error as err:
        print("query table 'mytable' failed.")
        print("Error: {}".format(err.msg))
        sys.exit()
     
    connection.commit()
    cursor.close()
    connection.close()

    输出:

    (1, 'Jay', 22)
    [(2, 'Tony', 26), (3, '邵', 24)]
    [(1, 'Jay', 22), (2, 'Tony', 26), (3, '邵', 24)]
    ID:1 Name:Jay Age:22
    ID:2 Name:Tony Age:26
    ID:3 Name:邵 Age:24

  • 相关阅读:
    高性能MySQL之锁详解
    采样方法-数据不均衡
    bert中的分词
    中文多分类 BERT
    Transformer+BERT+GPT+GPT2
    GPU下train 模型出现nan
    list 转换成dictionary,并统计词频
    python多个分割符split字符串
    tensorflow中的kernel/Adam 变量的来源
    tensorflow 使用预训练好的模型的一部分参数
  • 原文地址:https://www.cnblogs.com/windlaughing/p/3157531.html
Copyright © 2020-2023  润新知