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

时间:2021-06-25 17:19:20   收藏:0   阅读:0
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]+"\n")
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()

  

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!