将CSV文件插入SQL(空)表的python代码问题

时间:2019-08-08 19:02:34

标签: python sql

因此,我有以下代码使用“ {}”作为数据的占位符。但是,当我在SQL Server中检查表时,表中的{}已满,根本没有数据!如果我使用%s或%d等,则显示错误,如果使用?占位符我仍然收到错误。我已经尝试为所有列创建具有VARCHAR数据类型的表,但仍然无法正常工作。

我尝试了带引号的%s和%d,但没有逗号,也没有...不知道该怎么办:( 这是代码和相应的错误:

import pyodbc
print('Connecting...')

#Server in my PC:
conn = pyodbc.connect('Trusted_Connection=yes', DRIVER = '{ODBC Driver 13 for SQL Server}', SERVER = 'MYPRECIOUS', DATABASE = 'QAStore') 
print('Connected')
cursor = conn.cursor()
print('cursor established')

create_table = '''
DROP TABLE IF EXISTS UFO_GB_1;
CREATE TABLE UFO_GB_1
(Index_No int NOT NULL,
date_time datetime NOT NULL,
city_or_state VARCHAR(100) NULL, 
country_code VARCHAR(20) NULL,
shape VARCHAR (200) NULL,
duration float NULL, 
date_posted date NULL,
comments VARCHAR(700) NULL);
'''
cursor.execute(create_table)
conn.commit()
print('Table created')

SQL_string = '''INSERT INTO QAStore.[dbo].[UFO_GB_1]
([Index_No],[date_time],[city_or_state],[country_code],[shape],[duration],[date_posted],[comments])
VALUES ('?','?','?','?','?','?','?','?');'''

#Open the file as readable, and populate the table in SSMS with correct data cleaning
with open(r'UFO_Observations_1.csv','r') as file:   
    #file.readline() #Use if we want to skip header
    print('File read')
    for line in file:        
        cols = line.split(',')
        result = SQL_string.format(cols[0].replace('244', " "), cols[1], cols[2], cols[3], cols[4], cols[5], cols[6], cols[7].replace('&#44', ",")) 
        cursor.execute(SQL_string)
        conn.commit()
conn.close()
print('Table Ready')````



##Using VALUES ('?','?','?','?','?','?','?','?') I get this error

````Traceback (most recent call last):
  File "F:\DATA_ANALYSIS_LEVEL_QA\MODULE_2\Challenge_2\TASK_2\Task2_C2_MY_PC.py", line 99, in <module>
    cursor.execute(SQL_string)
pyodbc.DataError: ('22018', "[22018] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value '?' to data type int. (245) (SQLExecDirectW)")````

##With VALUES( %d, %s%s%s %s:%s, %s, %s, %s, %f, %d, %s%s%s ) I get this error:

````Traceback (most recent call last):
  File "F:\DATA_ANALYSIS_LEVEL_QA\MODULE_2\Challenge_2\TASK_2\Task2_C2_MY_PC.py", line 100, in <module>
    cursor.execute(SQL_string)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'd'. (102) (SQLExecDirectW)")````

##Using VALUES ('{}','{}','{}','{}','{}','{}','{}','{}') I get this error

````Traceback (most recent call last):
  File "F:\DATA_ANALYSIS_LEVEL_QA\MODULE_2\Challenge_2\TASK_2\Task2_C2_MY_PC.py", line 102, in <module>
    cursor.execute(SQL_string)
pyodbc.DataError: ('22018', "[22018] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value '{}' to data type int. (245) (SQLExecDirectW)")````

1 个答案:

答案 0 :(得分:0)

您要发送“?”和'{}'进入定义为整数的第一个字段。只能使用整数。

 Index_No int NOT NULL