python多进程拉取数据库数据

import multiprocessing
import psycopg2

def get_data(start, end):
    driver = '{ODBC Driver 17 for SQL Server}'
    username = ''
    server = ''
    database = ''
    password = ''
    con_str = f'DRIVER={driver};SERVER={server};PORT=1433;DATABASE={database};UID={username};PWD={password}'
    cnxn = pyodbc.connect(con_str)
    cur = cnxn.cursor()
    cur.execute("SELECT * FROM mytable WHERE id BETWEEN %s AND %s", (start, end))
    rows = cur.fetchall()
    conn.close()
    return rows

def main():
    pool = multiprocessing.Pool(processes=4)
    results = []
    for i in range(0, 100, 25):
        result = pool.apply_async(get_data, args=(i, i+25))
        results.append(result)
    pool.close()
    pool.join()
    for result in results:
        print(result.get())

if __name__ == '__main__':
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要通过Python连接数据库,需要使用相应的数据库驱动程序。以下是连接常见数据库的基本示例: 1. MySQL 使用Python的MySQL驱动程序 `mysql-connector-python` 来连接MySQL数据库。首先需要安装驱动程序,可以使用 `pip` 命令安装: ``` pip install mysql-connector-python ``` 连接MySQL数据库的示例代码如下: ```python import mysql.connector # 连接数据库 cnx = mysql.connector.connect(user='root', password='password', host='localhost', database='mydatabase') # 查询数据 cursor = cnx.cursor() query = ("SELECT id, name, age FROM mytable") cursor.execute(query) # 处理数据 for (id, name, age) in cursor: print("{} - {} - {}".format(id, name, age)) # 关闭连接 cursor.close() cnx.close() ``` 2. SQLite 使用Python的SQLite驱动程序 `sqlite3` 来连接SQLite数据库,这个驱动程序是Python标准库的一部分,不需要额外安装。连接SQLite数据库的示例代码如下: ```python import sqlite3 # 连接数据库 conn = sqlite3.connect('example.db') # 查询数据 cursor = conn.cursor() query = ("SELECT id, name, age FROM mytable") cursor.execute(query) # 处理数据 for (id, name, age) in cursor: print("{} - {} - {}".format(id, name, age)) # 关闭连接 cursor.close() conn.close() ``` 3. PostgreSQL 使用Python的PostgreSQL驱动程序 `psycopg2` 来连接PostgreSQL数据库。首先需要安装驱动程序,可以使用 `pip` 命令安装: ``` pip install psycopg2 ``` 连接PostgreSQL数据库的示例代码如下: ```python import psycopg2 # 连接数据库 conn = psycopg2.connect(database="mydatabase", user="myusername", password="mypassword", host="localhost", port="5432") # 查询数据 cursor = conn.cursor() query = ("SELECT id, name, age FROM mytable") cursor.execute(query) # 处理数据 for (id, name, age) in cursor: print("{} - {} - {}".format(id, name, age)) # 关闭连接 cursor.close() conn.close() ``` 以上示例代码只是演示如何连接数据库和查询数据,实际的查询语句和操作方式需要根据具体的数据库和表结构进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值