python连接mysql读取数据(总读取与分批读取)

import pymysql
import pandas as pd
import gc
import time
import threading

class Sql_df(object):
    def __init__(self,input_db):
        self.host = 'ip_xxx'
        self.port = 3306
        self.username = 'root'
        self.password = 'xxx'
        self.input_db = input_db
        self.conn = pymysql.connect(host = self.host,port = self.port,user = self.username,passwd = self.password,db = self.input_db,charset = 'utf8')
    def sql_input_all(self,sql_state):
        cur_1 = self.conn.cursor(cursor = pymysql.cursors.DictCursor)
        cur_1.execute(sql_state+' limit 1')
        column_df = cur_1.fetchall()
        column_list = column_df[0].keys()
        cur_2 = self.conn.cursor()
        start_time = time.time()
        cur_2.execute(sql_state)
        tmp_list = cur_2.fetchall()
        result_df = pd.DataFrame(list(tmp_list),columns = column_list)
        end_time = time.time()
        during_time = round(end_time-start_time,0)/60
        print('input data has spend %f minutes'%during_time)
        return result_df
    def sql_input_batch(self,sql_state,nums_sql_state,batch_size):
        cur_1 = self.conn.cursor(cursor = pymysql.cursors.DictCursor)
        cur_1.execute(sql_state+' limit 1')
        column_df = cur_1.fetchall()
        column_list = column_df[0].keys()
        cur_2 = self.conn.cursor()
        start_time = time.time()
        cur_2.execute(nums_sql_state)
        nums_sample = cur_2.fetchall()[0][0]
        batches = nums_sample//batch_size
        cur_3 = self.conn.cursor()
        result_df = pd.DataFrame()
        for i in range(batches):
            cur_3.execute(sql_state+' limit '+str(i*batch_size)+','+str(batch_size))
            tmp_list = list(cur_3.fetchall())
            tmp_df = pd.DataFrame(tmp_list,columns = column_list)
            del tmp_list
            gc.collect()
            result_df = result_df.append(tmp_df)
            del tmp_df
            gc.collect()
        last_index = batches*batch_size
        cur_3.execute(sql_state+' limit '+str(last_index)+','+str(nums_sample-last_index))
        tmp_list = list(cur_3.fetchall())
        tmp_df = pd.DataFrame(tmp_list,columns = column_list)
        result_df = result_df.append(tmp_df)
        end_time = time.time()
        during_time = round(end_time-start_time,0)/60
        print('input data has spend %f minutes'%during_time)
        del tmp_df
        gc.collect()
        return result_df

if __name__ == '__main__':
    #input_db = 'aid-livelihood'
    data_input = Sql_df('aid-livelihood')
    pa_visit_hypertension_2014_2016 = data_input.sql_input_all('select * from pa_visit_cerebral_infarction_2014_2015')
    #pa_visit_hypertension_2017_2018 = data_input.sql_input_all('select * from pa_visit_hypertension_2017_2018')
    #pa_inhosp_info = data_input.sql_input_all('select * from pa_inhosp_info')
    #rr = data_input.sql_input_batch('select * from pa_empi','select count(1) from pa_empi',5000)        

 

### 回答1: 要使用Python读取MySQL中的图片,需要以下步骤: 1. 安装PythonMySQL连接库,如mysql-connector-python或PyMySQL。 2. 连接MySQL数据库,并选择相应的数据库和表格。 3. 执行查询语句,选择需要读取的图片字段。 4. 将读取到的二进制数据保存为图片文件。 下面是一个简单的示例代码: ```python import mysql.connector import os connection = mysql.connector.connect( host="localhost", user="root", passwd="password", database="testdb" ) cursor = connection.cursor() cursor.execute("SELECT image_data FROM images WHERE id = 1") result = cursor.fetchone() if result: image_data = result[0] with open("image.jpg", "wb") as file: file.write(image_data) print("Image saved successfully!") else: print("Image not found.") cursor.close() connection.close() ``` 以上代码用于读取名为"images"的表格中id为1的记录的图片数据,并将其保存为"image.jpg"的文件。可根据实际需要修改相关参数和路径。 当然,如果图片数据较大,也可以通过分批读取等方式进行优化处理。 ### 回答2: 使用Python读取MySQL中的图片需要涉及到三个步骤:连接数据库、查询图片、保存图片。 1.连接数据库 Python连接MySQL可以使用官方提供的MySQL Connector模块,这个模块可以用pip安装。安装好后,就可以用下面的代码连接数据库了。 ```python import mysql.connector # 建立连接 cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='database_name') ``` 2.查询图片 在连接好数据库后,就可以使用MySQL中的SELECT语句查询图片了。在SELECT语句中,需要指定图片所在的表和字段名,并且查询出来的结果需要使用fetchone()方法获取,获取的结果是二进制数据类型。 ```python # 查询图片 cursor = cnx.cursor() query = ("SELECT image FROM image_table WHERE image_id = %s") cursor.execute(query, (image_id,)) image_data = cursor.fetchone()[0] # 获取图片二进制数据 ``` 3.保存图片 在获取到图片的二进制数据后,就可以使用Python的文件操作功能来保存图片。保存图片时,需要指定保存的文件名,并且将二进制数据以二进制方式写入文件。 ```python # 保存图片 with open("image.jpg", "wb") as image_file: image_file.write(image_data) # 将二进制数据写入文件 ``` 完整代码如下: ```python import mysql.connector # 建立连接 cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='database_name') # 查询图片 cursor = cnx.cursor() query = ("SELECT image FROM image_table WHERE image_id = %s") cursor.execute(query, (image_id,)) image_data = cursor.fetchone()[0] # 获取图片二进制数据 # 保存图片 with open("image.jpg", "wb") as image_file: image_file.write(image_data) # 将二进制数据写入文件 ``` 注意事项: 1. 在查询图片时,需要确保图片的字段类型是blob。 2. 在保存图片时,需要确保保存的文件名和路径正确。 ### 回答3: Python读取Mysql中的图片 Python是一门强大的编程语言,已经成为了许多开发者的首选,它可以通过各种方式读取Mysql中的图片,本文将带来两种常用的方式,分别是使用MySQLdb和PyMySQL库。 一、使用MySQLdb MySQLdb库是Python操作MySQL的标准库,它提供了对MySQL数据库的连接和操作的支持。基于MySQLdb,我们可以便捷地读取MySQL中的图片。 1.1 首先需要安装它,可以使用pip安装 ```python pip install MySQLdb ``` 1.2 配置数据库连接参数 ```python import MySQLdb # 配置数据库连接参数 db = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="test", charset='utf8') ``` 1.3 读取图片 ```python import MySQLdb # 配置数据库连接参数 db = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="test", charset='utf8') # 获取游标 cursor = db.cursor() # 执行SQL语句 sql = """SELECT photo FROM photos WHERE id=%s""" % (1) cursor.execute(sql) # 获取结果 result = cursor.fetchone() # 获取图片 photo = result[0] # 关闭数据库连接 db.close() ``` 1.4 保存图片 ```python import MySQLdb # 配置数据库连接参数 db = MySQLdb.connect(host="localhost", user="root", passwd="123456", db="test", charset='utf8') # 获取游标 cursor = db.cursor() # 执行SQL语句 sql = """SELECT photo FROM photos WHERE id=%s""" % (1) cursor.execute(sql) # 获取结果 result = cursor.fetchone() # 获取图片 photo = result[0] # 保存图片 with open('test.jpg', 'wb') as f: f.write(photo) # 关闭数据库连接 db.close() ``` 二、使用PyMySQL PyMySQLMySQLdb相似,同样是从Python操作MySQL数据库的库,但是它对Python3的支持更好,因此如果是Python3环境,建议使用PyMySQL。 2.1 安装库 ``` pip install PyMySQL ``` 2.2 配置数据库连接参数 ```python import pymysql # 配置数据库连接参数 conn = pymysql.connect(host='localhost', user='root', password='123456', db='test', charset='utf8') ``` 2.3 读取图片 ```python import pymysql import io from PIL import Image # 配置数据库连接参数 conn = pymysql.connect(host='localhost', user='root', password='123456', db='test', charset='utf8') # 获取游标 cursor = conn.cursor() # 执行SQL语句 sql = """SELECT photo FROM photos WHERE id=%s""" % (1) cursor.execute(sql) # 获取结果 result = cursor.fetchone() # 获取图片 img = Image.open(io.BytesIO(result[0])) # 关闭数据库连接 conn.close() ``` 2.4 保存图片 ```python import pymysql # 配置数据库连接参数 conn = pymysql.connect(host='localhost', user='root', password='123456', db='test', charset='utf8') # 获取游标 cursor = conn.cursor() # 执行SQL语句 sql = """SELECT photo FROM photos WHERE id=%s""" % (1) cursor.execute(sql) # 获取结果 result = cursor.fetchone() # 获取图片 photo = result[0] # 保存图片 with open('test.jpg', 'wb') as f: f.write(photo) # 关闭数据库连接 conn.close() ``` 以上就是Python读取Mysql中的图片的两种常用方式,可以根据自己的需要选择一种方式使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值