Inserting strings to a table in a loop - sql

Hi I'm trying to create tables in sqlite via sqlite3 in python3.
The code I got so far is:
import sqlite3
text="hello"
db = sqlite3.connect('C:/DB.db')
c = db.cursor()
c.execute("CREATE TABLE %s (sida)" % name)
for i in range(10):
c.execute("INSERT INTO %s VALUES (%s)" % (name, str(text))) # This does not work
db.commit()
db.close()
c.close
Changing the value from str(text) to i works;
c.execute("INSERT INTO %s VALUES (%s)" % (name, i)) # This works
Passing an integer as the value works but not a string. I've been trying to find a solution but I'm stuck.
The error I get is:
c.execute("INSERT INTO %s VALUES (%s)" % (name, str(text)))
sqlite3.OperationalError: near "a2": syntax error

You should be using a prepared statement for your inserts, binding values to any placeholders which exist:
c = db.cursor()
c.execute("CREATE TABLE %s (sida)" % name)
for i in range(10):
c.execute("INSERT INTO %s VALUES (?)" % name, (str(text),))
db.commit()
db.close()
c.close
Actually, it would also be better to not make the table name itself dynamic.

Related

No function matches the given name and argument types. You might need to add explicit type casts psql loop

I keep getting the error and I cant seem to solve it
ERROR: function partialdistanceh(integer, integer) does not exist
LINE 1: partialDistanceH(rHops.PlanetOrigin, rHops.PlanetDestination...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
QUERY: partialDistanceH(rHops.PlanetOrigin, rHops.PlanetDestination)
CONTEXT: PL/pgSQL function inline_code_block line 33 at EXECUTE
Code
FOR rHops IN SELECT PlanetOrigin, PlanetDestination FROM Hops
LOOP
PREPARE partialDistanceB (INT, INT) AS
SELECT AvgDistance FROM Distance
WHERE PlanetOrigin = $1
AND PlanetDestination = $2;
EXECUTE partialDistanceB(rHops.PlanetOrigin, rHops.PlanetDestination);
hopDistance = partialDistance;
routeDistance = routeDistance + hopDistance;
END LOOP;

SQL Expected end of input but got keyword WHERE

I am performing a SQL query using Python for a Big Query data set. I am getting an error and I could not figure out what do I need to fix on my own. This is the error log:
Expected end of input but got keyword WHERE
The variable vector_score is a float (I also tried with an int and does the same thing)
Query:
sql = f"""
SET lauder = lauder * %f
WHERE keyword= '%s'
AND (date BETWEEN '%s' AND '%s')
""" % (vector_score, keyword, starting_date, ending_date)
Parameters:
vector_score = 1.05
keyword = food
starting_date = '2020-01-10'
ending_date = '2020-01-17'
You are missing the actual update command in your execution
UPDATE TARGET_NAME
SET lauder = lauder * %f
WHERE keyword= '%s'
AND (date BETWEEN '%s' AND '%s')

Querying multiple postgres tables in python

I'm trying to query multiple sql tables and store them as pandas dataframe.
cur = conn.cursor()
cur.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
tables_df = cur.fetchall()
##table_name_list = tables_df.table_name
select_template = ' SELECT * FROM {table_name}'
frames_dict = {}
for tname in tables_df :
query = select_template.format(table_name = tname)
frames_dict [tname] = pd.read_sql ( query , conn)
But I'm getting error like :
DatabaseError: Execution failed on sql ' SELECT * FROM ('customer',)': syntax
error at or near "'yesbank'"
`enter code here`LINE 1: SELECT * FROM ('customer',)
Customer is name of table in my databse that i get from line
tables_df = cur.fetchall()
Per your error, looks like you have a typo in the word format:
AttributeError: 'str' object has no attribute 'formate'
Try
query = select_template.format(table_name = tname)

Remove quotes from string for SQL and insert into Postgres

I want to remove the quotes from each end of string for SQL insert into Postgres.
At the moment my code looks like this:
label='ave_number'
sql_cmd=u"""UPDATE rpt.so_form2_test_noquotes SET %s=%s WHERE channel_id=%s and report_id=%s and load_date=current_date;"""
sql_params=(label, e[u"label"],channel_id,report_id,)
calldb(conn, sql_cmd, sql_params)
def calldb( db, sql_cmd, sql_params): # invoke backend function that is a INSERT/UPDATE statement
try:
cur = db.cursor() # use standard cursor as return is likely void
print 'Executing sql cmd "{0}"'.format(cur.mogrify(sql_cmd, sql_params))
cur.execute(sql_cmd, sql_params)
return # execute returns None expected
except Exception as e:
print u'Error ', e
raise
My Postgres column name is ave_number with no quotes. When the %s get substitued with the string it gives me an error saying there is no column called 'ave_number'.
Thanks in advance
I think you need to use AsIs from psycopg2.extensions
from psycopg2.extensions import AsIs
import psycopg2
def calldb( db, sql_cmd, sql_params): # invoke backend function that is a INSERT/UPDATE statement
try:
cur = db.cursor() # use standard cursor as return is likely void
print 'Executing sql cmd "{0}"'.format(cur.mogrify(sql_cmd, sql_params))
cur.execute(sql_cmd, sql_params)
return # execute returns None expected
except Exception as e:
print u'Error ', e
raise
conn = psycopg2.connect(host='localhost', port=5432, user='xxxxxxx', password='xxxxxx')
label='ave_number'
e={u'label':'test_label'}
channel_id=1
report_id=1
sql_cmd=u"""UPDATE rpt.so_form2_test_noquotes SET %s=%s WHERE channel_id=%s and report_id=%s and load_date=current_date;"""
sql_params=(AsIs(label), e[u"label"],channel_id,report_id,)
calldb(conn, sql_cmd, sql_params)
which outputs this
Executing sql cmd "UPDATE rpt.so_form2_test_noquotes SET ave_number='test_label' WHERE channel_id=1 and report_id=1 and load_date=current_date;"

XMLQuery with Oracle

I'm doing examples from workbook. I created table and insert couple of records. Below is my code:
Create table:
CREATE TABLE test_Pracownicy
(IDPracownika NUMBER(3),
Dane XMLTYPE);
Insert record to the table:
INSERT INTO test_Pracownicy (IDPracownika, Dane)
VALUES (1,
XMLTYPE('
<PRecord>
<Nazwisko>Kowalski</Nazwisko>
<Imie>Jan</Imie>
<RokUrodz>1980</RokUrodz>
<Wzrost>1.77</Wzrost>
<DataZatr>2001/02/10</DataZatr>
</PRecord>')
);
Now I want to run XMLQuery:
SELECT IDPracownika,
XMLQuery(
'FOR $i IN /PRecord
WHERE $i /Nazwisko = "Kowalski"
ORDER BY $i/Imie
RETURN $i'
PASSING by VALUE Dane
RETURNING CONTENT) NazwiskoXML
FROM test_Pracownicy;
and I'm getting error:
ORA-19114: XPST0003 - error during parsing the XQuery expression:
LPX-00801: XQuery syntax error at 'i'
1 FOR $i IN /PRecord
- ^
19114. 00000 - "error during parsing the XQuery expression: %s"
*Cause: An error occurred during the parsing of the XQuery expression.
*Action: Check the detailed error message for the possible causes.
Error at Line: 117 Column: 6
I changed query to small (for, where, return...) letters and it's workging:
SELECT IDPracownika,
XMLQuery(
'for $i in /PRecord
where$i /Nazwisko = "Kowalski"
order by $i /Imie
retrun $i'
PASSING by VALUE Dane
RETURNING CONTENT) NazwiskoXML
FROM test_Pracownicy;
It's case sensitive.