zoukankan      html  css  js  c++  java
  • 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()
    

      

  • 相关阅读:
    关于yyyy-MM-dd格式日期字符串,解析成LocalDateTime遇到的问题
    idea设置代码提示不区分大小写
    不错的Django技术网址
    Django-Rest-Framework 教程: 快速入门
    Djanto static静态文件配置
    Html5 touch event
    Zepto.js touch模块深入分析
    Python单元测试框架之pytest -- fixtures
    Python:高级主题之(属性取值和赋值过程、属性描述符、装饰器)
    Nginx基本配置、性能优化指南
  • 原文地址:https://www.cnblogs.com/gzhbk/p/14930592.html
Copyright © 2011-2022 走看看