zoukankan      html  css  js  c++  java
  • 使用Python与数据库交互

    # -*- coding: utf-8 -*-
    """
    Created on Sun Nov 18 19:25:01 2018
    
    @author: wangm
    """
    
    # 使用Python自带的sqlite3模块
    # 创建数据库中的表、在表中插入数据、以及在输出中获取数据并对行进行计数
    #!/usr/bin/env python3
    # 导入sqlite3模块
    import sqlite3
    
    # 创建一个代表数据库的连接对象,此处使用专用名词 ':memory:' 在内存中创建一个数据库
    # 也可以使用其他名字,此时创建的数据库会被保存在你的工作目录,或者自己指定的路径下
    con = sqlite3.connect(':memory:')
    #con = sqlite3.connect('mydatabase')
    # 创建表sales,具有四个属性
    # 此处query内有多行,使用 “”“
    query = """create table sales 
               (customer varchar(20), 
               product varchar(40), 
               amount float, date DATE);"""
    # 执行query中的sql命令
    con.execute(query)
    # 将对数据库做的修改提交,即保存到数据库中
    con.commit()
    
    # 在表中插入四行数据
    data = [('AAA', 'Apple', 10000.0, '2018-01-01'), 
            ('BBB', 'Huawei', 5000.0, '2018-02-01'), 
            ('CCC', 'Mi', 3000.0, '2018-03-01')]
    # 此处statement只有一行,所以可以用 “
    # 此处 ? 为占位符,在connect对象的con.execute()或con.executemany()方法中,需要提供
    # 一个包含四个值得元组,元组中的值会按位置替换到sql语句中
    # 这种替换的方法还有一个好处是可以防止SQL注入攻击
    statement = "insert into sales values(?, ?, ?, ?)"
    # 为data中的每条数据元组都执行statement中的命令,此处执行四次
    con.executemany(statement, data)
    # 注意此处不能用con.execute()方法
    # 出错信息:ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 3 supplied.
    #con.execute(statement, data)
    con.commit()
    
    # 查询sales表
    # 执行SQL语句"select * from sales",并将结果赋给一个光标对象cursor
    cursor = con.execute("select * from sales")
    # fetchall()取出SQL返回结果的所有行,并将这些行赋给rows
    rows = cursor.fetchall()
    # rows 的类型 <class 'list'>
    #print(type(rows))
    
    # 输出查询到的每一行,并对行计数
    #row_counter = 0
    #for row in rows:
        #print(row)
        #row_counter += 1
    #print('row_counter is %d' % (row_counter))
    
    """
    输出结果:
    ('AAA', 'Apple', 10000.0, '2018-01-01')
    ('BBB', 'Huawei', 5000.0, '2018-02-01')
    ('CCC', 'Mi', 3000.0, '2018-03-01')
    row_counter is 3
    """
    
    # 根据上述的这些对SQL的操作,和前面的关于对CSV文件、Excel文件的操作,就可以很简单的
    # 将一个CSV文件或Excel文件存储到数据库中,成为数据库中的一张表
    # 以CSV文件为例,即读取CSV文件每一行数据,使用insert,插入到数据库中
    
    # 除了上述的创建数据库、创建表、向表中插入数据、查询表中的数据之外
    # 也可以在con.execute()中执行其他的插删改操作
    
    # 插入:
    con.execute("insert into sales values(?, ?, ?, ?)", ('DDD', 'MeiZu', 2000.0, '2018-04-01'))
    con.commit()
    
    cursor = con.execute("select * from sales")
    rows = cursor.fetchall()
    row_counter = 0
    for row in rows:
        print(row)
        row_counter += 1
    print('row_counter is %d' % (row_counter))
    
    # 修改
    temp = [2500.0, '2018-05-01', 'DDD']
    con.execute("update sales set amount=?, date=? where customer=?;", temp)
    con.commit()
    cursor = con.execute("select * from sales")
    rows = cursor.fetchall()
    row_counter = 0
    for row in rows:
        print(row)
        row_counter += 1
    print('row_counter is %d' % (row_counter))
    
    # 删除
    temp = ['CCC']
    con.execute("delete from sales where customer=?;", temp)
    con.commit()
    cursor = con.execute("select * from sales")
    rows = cursor.fetchall()
    row_counter = 0
    for row in rows:
        print(row)
        row_counter += 1
    print('row_counter is %d' % (row_counter))
    
    """
    输出结果:
    ('AAA', 'Apple', 10000.0, '2018-01-01')
    ('BBB', 'Huawei', 5000.0, '2018-02-01')
    ('CCC', 'Mi', 3000.0, '2018-03-01')
    ('DDD', 'MeiZu', 2000.0, '2018-04-01')
    row_counter is 4
    ('AAA', 'Apple', 10000.0, '2018-01-01')
    ('BBB', 'Huawei', 5000.0, '2018-02-01')
    ('CCC', 'Mi', 3000.0, '2018-03-01')
    ('DDD', 'MeiZu', 2500.0, '2018-05-01')
    row_counter is 4
    ('AAA', 'Apple', 10000.0, '2018-01-01')
    ('BBB', 'Huawei', 5000.0, '2018-02-01')
    ('DDD', 'MeiZu', 2500.0, '2018-05-01')
    row_counter is 3
    
    """

    上述代码(以Python内置的sqlite为例)展示了如何连接数据库,并在数据库中新建table,并对table进行增删改查操作

    而下面在我准备连接MySQL时,出现下列错误:

    #!/usr/bin/env python3
    import csv
    import MySQLdb
    #from datetime import datetime, date
    
    input_file = 'D:wangmDocumentslearningcodepythonsupplier_data.csv'
    
    con = MySQLdb.connect(host='localhost', port=3306, db='test', user='root', passwd='1126')
    c = con.cursor()
    """
    file_reader = csv.reader(open(input_file, 'r', newline=''))
    header = next(file_reader)
    for row in file_reader:
        data = []
        for column_index in range(len(header)):
            data.append(str(row[column_index]).lstrip('$').replace(',', '').strip())
        print(data)
        c.execute("insert into supplier values (%s, %s, %s, %s, %s);", data)
    con.commit()
    print('')
    """

    错误信息:OperationalError: (2059, <NULL>)

    在网上找到的错误原因:MySQL8.0使用的新的认证加密方式导致了这种犯错误

    具体可以查看此处:https://blog.csdn.net/rbborb/article/details/80541468

    根据上述文章,我尝试更新以下相关的库,更新后相关库的版本如下:

    再次运行上述代码,依然报错。

    上述文章还提供另一种方法,卸载MySQL,选择之前版本

  • 相关阅读:
    如何搜索 git 提交记录
    使用Mongo进行分页
    mongodb 数据自动备份
    linux 添加环境变量
    centos7安装bbr
    centos7安装node
    [shell]输出内容到剪切板
    centos 7 已经开启 22 端口但无法连接
    一些有趣的 js 包
    机房选择
  • 原文地址:https://www.cnblogs.com/lnlin/p/10027421.html
Copyright © 2011-2022 走看看