You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中处理SQL Server查询结果以单独发送短信

解决SQL Server查询结果的逐行处理问题

看起来你已经成功从SQL Server拉到数据了,核心问题就是怎么把每条记录拆出来,生成对应的短信内容并调用API发送对吧?咱们一步步来搞定:

1. 先确认数据结构

你执行的是SELECT name, phone, date FROM Table1,所以final_result里的每个子列表应该是[姓名, 手机号, 预约日期]三个元素。你之前打印的示例里没显示日期,应该是简化了,实际代码里要保证date字段被正确获取到哦。

2. 遍历结果,逐行处理

用一个简单的for循环就能遍历每条记录,然后提取字段生成短信:

# 先把你已经实现的短信API函数放这里,比如叫send_sms
def send_sms(phone_number, message):
    # 这里是你写好的API调用逻辑,我用打印代替示例
    print(f"发送短信到 {phone_number}: {message}")

# 遍历从数据库拿到的结果
for row in final_result:
    # 从每行里提取三个字段
    name = row[0]
    phone = row[1]
    appointment_date = row[2]
    
    # 处理日期格式:如果数据库返回的是datetime对象,转成你要的"DD/MM/YYYY"格式
    # 如果本来就是字符串,直接用就行
    formatted_date = appointment_date.strftime("%d/%m/%Y") if hasattr(appointment_date, 'strftime') else appointment_date
    
    # 生成短信内容
    sms_message = f"Dear {name}, tomorrow ({formatted_date}) you have an appointment in the Clinic"
    
    # 调用短信API发送
    send_sms(str(phone), sms_message)  # 手机号转成字符串,避免API接收格式问题

3. 额外的优化建议

  • 异常处理:加个try-except块,防止某一条记录处理失败导致整个程序停掉:
for row in final_result:
    try:
        name = row[0]
        phone = str(row[1])
        appointment_date = row[2]
        formatted_date = appointment_date.strftime("%d/%m/%Y") if hasattr(appointment_date, 'strftime') else appointment_date
        sms_message = f"Dear {name}, tomorrow ({formatted_date}) you have an appointment in the Clinic"
        send_sms(phone, sms_message)
        print(f"成功给{name}发送短信")
    except Exception as e:
        print(f"处理记录{row}时出错:{str(e)}")
  • 数据类型校验:如果数据库里的手机号是整数类型,转成字符串再传给API,很多短信接口都要求手机号是字符串格式。

完整整合后的代码

把这些逻辑加到你的现有代码里,最终版本大概是这样:

import pypyodbc

# 替换成你实际的短信API函数
def send_sms(phone_number, message):
    # 这里写你的API调用代码,比如调用第三方短信接口
    print(f"[短信API] 发送到 {phone_number}: {message}")

# 数据库连接(你的参数已经能正常工作,直接用)
conn = pypyodbc.connect("Connection parameters, working OK")
cursor = conn.cursor()
cursor.execute('SELECT name, phone, date FROM Table1')
result = cursor.fetchall()
final_result = [list(i) for i in result]

# 逐行处理数据并发送短信
for row in final_result:
    try:
        name = row[0]
        phone = str(row[1])  # 确保手机号是字符串
        appointment_date = row[2]
        
        # 格式化日期,兼容datetime对象和字符串
        if hasattr(appointment_date, 'strftime'):
            formatted_date = appointment_date.strftime("%d/%m/%Y")
        else:
            formatted_date = appointment_date
        
        # 生成短信内容
        sms_content = f"Dear {name}, tomorrow ({formatted_date}) you have an appointment in the Clinic"
        
        # 发送短信
        send_sms(phone, sms_content)
        
    except Exception as e:
        print(f"处理记录失败 {row}: {str(e)}")

# 记得关闭数据库连接
conn.close()

这样就能把每条数据都单独处理,生成对应的短信并发送了。如果还有具体的格式问题或者数据类型异常,随时说细节哦!

内容的提问来源于stack exchange,提问作者Nyrah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:32:53