• python连接mysql数据库把取数据存入数据库


    •   安装pymysql库
    pip install pymysql
    
    •   建存储数据表
    
    

    CREATE DATABASE `stock` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */;


    -- stock.stock_all_codes definition CREATE TABLE `stock_all_codes` ( `code` varchar(100) NOT NULL COMMENT '股票代码' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='股票代码表';

      

    • 连接数据源
    import pymysql
    db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='stock')
    cursor = db.cursor()
    sql = 'select * from stock_all_codes;'
    #查询sql
    print(sql)
    cursor.execute(sql)
    cursor.close()
    db.close()
    

      

    • 查询数据库
    # -*- coding: UTF-8 -*-
    import pymysql

    # 打开数据库连接
    db = pymysql.connect(host="localhost", user="root", passwd="123456", db="stock", charset='utf8' )

    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    # SQL 查询语句
    sql = "SELECT * FROM stock_all_codes"
    try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    print("代码")
    for it in results:
    for i in range(len(it)):
    print(it[i]+" ")
    except:
    print("Error: unable to fecth data")

    # 关闭数据库连接
    cursor.close()
    db.close()

      

    • 插入数据
    import pymysql
    db = pymysql.connect(host='localhost',user='root', password='123456', port=3306, db='stock')
    cursor = db.cursor()
    # 多字段动态插入mysql数据库中,data,添加字段
    data = {
        'code': 'sh000001'
    }
    table = 'stock_all_codes'
    keys = ', '.join(data.keys())
    values = ', '.join(['%s'] * len(data))
    sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
    try:
        cursor.execute(sql, tuple(data.values()))
        print('入库成功!')
        db.commit()
    except:
        print('入库失败')
        db.rollback()
    cursor.close()
    db.close()
    

      

    • 更新数据
    import pymysql
    db = pymysql.connect(host='localhost',user='root', password='123456', port=3306, db='stock')
    cursor = db.cursor();
    data = {
        'code': 'sh00002'
    }
    table = 'stock_all_codes'
    keys = ', '.join(data.keys())
    values = ', '.join(['%s'] * len(data))
    sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table, keys=keys, values=values)
    update = ','.join([" {key} = %s".format(key=key) for key in data])
    sql += update
    try:
        cursor.execute(sql, tuple(data.values())*2)
        print('更新成功')
        db.commit()
    except:
        print('更新失败')
        db.rollback()
    cursor.close()
    db.close()
    

      

  • 相关阅读:
    兄弟连新版ThinkPHP视频教程2.ThinkPHP 3.1.2 MVC模式和URL访问
    兄弟连新版ThinkPHP视频教程1.ThinkPHP 3.1.2 介绍及安装
    【算法】高效计算n的m次方
    linux下解压.zip压缩包出现乱码的问题解决
    马哥linux笔记--重定向
    JavaScript的基本知识
    repeater做删除前弹窗询问
    网页中图片路径错误时显示默认图片方法
    添加分页
    javascript类型转换
  • 原文地址:https://www.cnblogs.com/gzhbk/p/14930592.html
Copyright © 2020-2023  润新知