У меня небольшая проблема с фрагментом кода, я скопировал его из сети, но у меня есть следующая ошибка:
Sqlite3.OperationalError: рядом с "(": синтаксическая ошибка
Код следующий:
# Import required modules
import csv
import sqlite3
# Connecting to the geeks database
connection = sqlite3.connect('isaDBCommune.db')
# Creating a cursor object to execute
# SQL queries on a database table
cursor = connection.cursor()
# Table Definition
create_table = '''CREATE TABLE IF NOT EXISTS isaCommune(
id_codedep_codecommune INTEGER NOT NULL,
nom_commune TEXT NOT NULL,
code_postal INTEGER NOT NULL,
code_commune INTEGER NOT NULL,
code_departement INTEGER NOT NULL,
nom_departement TEXT NOT NULL,
code_region INTEGER NOT NULL
)'''
# Creating the table into our
# database
cursor.execute(create_table)
# Opening the person-records.csv file
file = open('commune.csv')
# Reading the contents of the
# person-records.csv file
contents = csv.reader(file)
# SQL query to insert data into the
# person table
insert_records = "INSERT INTO isaCommune (id_codedep_codecommune, nom_commune, code_postal, code_commune, code_departement, nom_departement, code_region) VALUES ('id_codedep_codecommune', 'nom_commune', 'code_postal', 'code_commune', 'code_departement', 'nom_departement', 'code_region')"
# Importing the contents of the file
# into our person table
cursor.executemany (insert_records, contents)
# SQL query to retrieve all data from
# the person table To verify that the
# data of the csv file has been successfully
# inserted into the table
select_all = "SELECT * FROM isaCommune"
rows = cursor.execute(select_all).fetchall()
Каким будет решение? Я искал по всему Stack Overflow, и я не могу найти решение
СПАСИБО
Любое решение? Или объяснение этой ошибке, что для меня скрыто?
Новая ошибка с исправлением...
Sqlite3.ProgrammingError: предоставлено неверное количество привязок. В текущем операторе используется 0, а имеется 1.
Ошибка sqlite3.OperationalError: в таблице isaCommune нет столбцов с именами «id_codep_codecommune», «nom_commune», «code_postal», «code_commune», «code_departement», «nom_departement», «code_region». 'nom_commune', 'code_postal', 'code_commune', 'code_departement', 'nom_departement', 'code_region']) ЗНАЧЕНИЯ (['id_codedep_codecommune', 'nom_commune', 'code_postal', 'code_commune', 'code_departement', 'nom_departement ', 'регион_кода'])"
Вам нужно заменить '?' по значению, которое вы хотите вставить в соответствующий столбец в зависимости от его типа INTEGER, TEXT и т.д..
Например:
insert_records = "INSERT INTO isaCommune VALUES(1, 'test', 1, 1, 1, 'test', 1) ('id_codedep_codecommune', 'nom_commune', 'code_postal', 'code_commune', 'code_departement', 'nom_departement', 'code_region')"
Я читаю из csv, может быть, там ошибка? id_codedep_codecommune;nom_commune;code_postal;code_commune;code_departement;nom_departement;code_region 1001;L ABERGEMENT CLEMENCIAT;1400;1;1;Ain;84
Insert_records = "ВСТАВИТЬ В ЗНАЧЕНИЯ isaCommune (id_codedep_codecommune, 'nom_commune', code_postal, code_commune, code_departement, 'nom_departement', code_region) ('id_codedep_codecommune', 'nom_commune', 'code_postal', 'code_commune', 'code_departement', 'nom_departement , 'код_регион') " sqlite3.OperationalError: рядом "(": синтаксическая ошибка
Это будет ваш ответ: -
import csv
import sqlite3
connection = sqlite3.connect('isaDBCommune.db')
cursor = connection.cursor()
create_table = '''CREATE TABLE IF NOT EXISTS isaCommune(
id_codedep_codecommune TEXT NOT NULL,
nom_commune TEXT NOT NULL,
code_postal TEXT NOT NULL,
code_commune TEXT NOT NULL,
code_departement TEXT NOT NULL,
nom_departement TEXT NOT NULL,
code_region TEXT NOT NULL
)'''
cursor.execute(create_table)
file = open('commune.csv')
contents = csv.reader(file)
for l in contents:
insert_records = """INSERT INTO isaCommune ('id_codedep_codecommune', 'nom_commune', 'code_postal','code_commune','code_departement','nom_departement','code_region')
VALUES(?,?,?,?,?,?,?)"""
a = (l[0],l[1],l[2],l[3],l[4],l[5],l[6],)
cursor.execute(insert_records, a)
select_all = "SELECT * FROM isaCommune"
rows = cursor.execute(select_all).fetchall()
for row in rows:
print(row)
Надеюсь теперь получится...
Нет.... a = (l[0],l[1],l[2],l[3],l[4],l[5],l[6],) IndexError: список индексов из диапазон Как я могу отправить вам файл csv???
Если в вашем CSV-файле 7 столбцов, он должен работать.
Сколько полей в вашем CSV-файле???
7 полей через запятую
'1001,LABERGEMENCLEMENCIAT,1400,1,1,Ain,84' Нравится??
Отлично, ваш код сработал отлично, отлично. Ставлю проблема решена!!!
Должно быть INSERT INTO isaCommune ([list of column names]) VALUES ([list of values]) вам нужно заполнить список имен столбцов и список значений.