python连接mysql数据库把取数据存入数据库
时间:2021-06-25 17:19:20
收藏:0
阅读:0
- 安装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]+"\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)