syntax error unexpected character after line continuation character - python

Can anybody tell me what's wrong in my program? When I run this program I get the following error message:
syntaxerror unexpected character after line continuation character
import sqlite3
sqlite_file = 'my_first_db.sqlite' # NAME OF THE SQL DATABASE FILE
table_name1 = 'my_table_1' # NAME OF THE TABLE THAT TO BE CREATED.
table_name2 = 'my_table_2' # NAME OF THE SECOND TABLE THAT TO BE CREATED.
new_filed = 'my_1st_coulmn' # NAME OF THE COULMN
filed_type = 'INTEGER' # COULMN DATA TYPE
# CONNECTING TO DATA BASE FILE
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
# CREATEING NEW SQLITE TABLE WITH 1 COULMN
c.execute('create table {tn} ({nf}) {ft})'\ .format(tn=table_name1,nf=new_filed,ft=filed_type))
# Creating a second table with 1 column and set it as PRIMARY KEY
# note that PRIMARY KEY column must consist of unique values!
c.execute('create table {tn} ({nf}) {ft} primary key)'\.format(tn=table_name2,nf=new_filed,ft=filed_type))
# Committing changes and closing the connection to the database file
conn.commit()
conn.close()

\ is used for line continuation while writing long queries.
so just remove \ before .format() at creation and execution of query if you continued the code after .
# CREATEING NEW SQLITE TABLE WITH 1 COULMN
c.execute('create table {tn} ({nf}) {ft})'.format(tn=table_name1,nf=new_filed,ft=filed_type))
and for more info read this.. https://pyformat.info/

Related

sqlite3.OperationalError: near "(": syntax error Python " SQL Lite [duplicate]

This question already has answers here:
Passing SQLite variables in Python
(1 answer)
How to use variables in SQL statement in Python?
(5 answers)
Closed last month.
I have a small problem with a piece of code, I copied it from a web, but I have the following error:
sqlite3.OperationalError: near "(": syntax error
The code is the following:
# 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()
What would be the solution? I have searched all over Stack Overflow and I can't find the solution
THX
Any solution ? Or explanation to this error that for me is hidden?
New error with correction ...
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
This will be your answer:-
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)
Hope it will work now...
You need to replace the '?' by the value you want to insert in the corresponding column depending on its type INTEGER, TEXT etc..
For example:
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')"

mysql LOAD DATA INFILE of csv from python (Not Working)

After some data manipulation I store two columns in a txt file in a csv format as following:
result.txt ->
id,avg
0,38.0
1,56.5
3,66.5
4,48.666666666666664
then I store the data in a table, which is where i find trouble, i tried running a .sql query that stores the data successfully, but executing the same query from python doesnt seem to work for some reason.
python code->
.
.
.
open('C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/result.txt', 'w').write(res)
print(res)
try:
with mysql.connector.connect(
host="localhost",
user='root',
password='tt',
database="dp",
) as connection:
clear_table_query = "drop table if exists test_db.marks;"
create_table_query = '''
create table test_db.marks (
id varchar(255) not null,
avg varchar(255) not null,
primary key (id)
);
'''
# droping the table and recreating it works fine
add_csv_query = "LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/result.txt' INTO TABLE marks FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES;"
print(add_csv_query) # query is printed correctly
with connection.cursor() as cursor:
cursor.execute(clear_table_query)
cursor.execute(create_table_query)
cursor.execute(add_csv_query)
cursor.execute("SELECT * FROM test_db.marks;") # this produces -> Unread result found
except mysql.connector.Error as e:
print(e)
connection.close()

Is there a way using SQLite and Python to write an insert statement with the columns as parameters?

I am trying to clean raw json data by parsing and inserting it into a table of an sqlite db.
I have 22 columns in my table and want to find a way of looping through them so I don't need to write 22 loops which insert the data or a single column.
I have simplified the approach I am trying with the following:
import sqlite3
conn = sqlite3.connect('cdata.sqlite')
cur = conn.cursor()
column = 'name'
value = 'test'
cur.execute('''INSERT INTO COMPANY (?)
VALUES (?)''',(column,),(value,))
conn.commit()
conn.close()
This doesn't work at the moment and return the error TypeError: function takes at most 2 arguments (3 given).
Does anyone know if it is possible to write an SQLite insert statement using 2 parameters like this or another way I might be able to iterate through the columns?
Sample as below:
import sqlite3
conn = sqlite3.connect("cdata.sqlite")
cur = conn.cursor()
column = ("name", "age")
table = f"CREATE TABLE IF NOT EXISTS COMPANY ({column[0]} text, {column[1]} text);"
cur.execute(table)
name = "hello"
age = "1"
sql_stmt = f"INSERT INTO COMPANY({column[0]},{column[1]}) VALUES ('{name}', '{age}')"
cur.execute(sql_stmt)
with conn:
cur.execute("SELECT * FROM COMPANY")
print(cur.fetchall())
conn.commit()
conn.close()

sqlite3 insert not committing

When trying to insert rows into a table with a unique index, it appears to simply silently not insert.
I've captured the behaviour in the following program: on the second call to test_insert I should get an integrity violation on the unique key. But nothing. Also, if I take the c.execute(query, [id_to_test]) line and duplicate itself below it, I do receive the proper integrity constraint as expected. What's happening here?
import sqlite3
def test_insert(id_to_test):
conn = sqlite3.connect('test.db')
c = conn.cursor()
query = '''INSERT INTO test(unique_id)
VALUES(?)'''
c.execute(query, [id_to_test])
def setup_table():
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('''DROP TABLE IF EXISTS test''')
c.execute('''CREATE TABLE test (unique_id text)''')
c.execute('''CREATE UNIQUE INDEX test_unique_id ON test (unique_id)''')
if __name__ == '__main__':
setup_table()
test_insert('test_id')
test_insert('test_id')
test_insert('test_id')
At the end of database operations, commit the changes to the database:
conn.commit()

"No such column" when checking for table column

I am creating a table to add data to a database but I am not sure where to create the column for 'emails'. My final aim for this is to be able to enter a username (email) and password and for it to be saved into a database but I am not sure how to do this. Here is my code currently:
import sqlite3
def save_to_database(my_stack, filename = 'stack_database.db'):
conn = sqlite3.connect(filename)
c = conn.cursor()
for row in c.execute('SELECT email FROM sqlite_master WHERE type="table"'):
if row != None:
c.execute("DROP TABLE emails")
c.execute("CREATE TABLE emails(email text,login_date text)")
...
The sqlite_master table does not have a column named email; the entire table structure is contained in the text in the sql column.
You could check for the table name itself (but note that if no row is found, no row is returned, not even an empty one, so it does not make sense to try to handle this with a for loop):
c.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'emails'")
if not c.fetchall():
c.execute('DROP TABLE emails')
However, there is an easier method to ensure that a table is removed, regardless of its previous state:
c.execute('DROP TABLE IF EXISTS emails')

Categories