ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Python连接MySQL或者SQLserver实现批量查询,数据库表名参数化,字段参数化

2020-03-05 10:37:02  阅读:55  来源: 互联网

标签:name sql Python reader 参数 str 表名 table line



Python连接数据库查询时,需注意sql语句的语法

1、数据库表名参数化,用format

file = 'tables.csv'
with open(file) as f:
    table_names = csv.reader(f)
    for table_name in table_names:
        print(table_name)
        sql = "SELECT * FROM {0}".format(table_name[0])
        conn = pyodbc.connect(driver=driver, server=server, user=user,
                              password=password, database=database)
        cur = conn.cursor()  # 创建一个游标(cursor)
        cur.execute(sql)

2、列名参数化

with open(file_name) as f_obj:
    reader = csv.reader(f_obj)
    ID = 0
    for line in reader:
        if reader.line_num == 1:
            continue
        print(line)

        ID += 1
        cclient_Name = line[0]
        sex = line[1]
        hospital = line[2]
        deparment = line[3]
        specialist = line[4]
        dbespoke_Time = line[5]
        week_day = line[6]
        serve_Sort = line[7]
        insert_sql = "insert into %s(ID,%s)values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \
                         % (table_name, ",".join(header), int(ID), line[0],
                            str(line[1]), str(line[2]), str(line[3]),
                            str(line[4]), str(line[5]), str(line[6]),
                            str(line[7]))
        # print(insert_sql)


标签:name,sql,Python,reader,参数,str,表名,table,line
来源: https://blog.csdn.net/sweetCat009/article/details/104669339

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有