Python SQLite3 Execution Error - python

Using python 2.7.5, I've written the following code down to compile based off of an online course I'm taking that shows how sqlite3 works with python
import sqlite3 as sql
database1 = sql.connect('test1.db')
db1_cursor = database1.cursor()
cmd = 'CREATE TABLE IF NOT EXISTS users(username TEXT,password TEXT)'
cmd2 = 'INSERT INTO users(username,password) VALUES("testuser,testpassword")'
cmd3 = 'SELECT username,password FROM users'
db1_cursor.execute(cmd)
db1_cursor.execute(cmd2)
db1_cursor.execute(cmd3)
database1.commit()
for x in db1_cursor:
print(x)
Now, upon running this code it gives me the following operation error:
Traceback (most recent call last):
File "C:\Users\Ryan\My Code Projects\Learning\udemycourse.py", line 11, in <module>
db1_cursor.execute(cmd2)
OperationalError: 1 values for 2 columns
Why does it give this error for db1_cursor.execute(cmd2) but not for db1_cursor.execute(cmd1) and how can I fix this?

I think you meant
Values ("testuser","testpassword")

A better way of doing the insert would be
cmd2 = 'INSERT INTO users(username,password) VALUES(?, ?)'
Creating placeholders
db1_cursor.execute(cmd2, ('testuser','testpassword'))
and passing the values as a tuple

Related

pyodbc insert statement gets error message

I am trying to insert value into SQL SERVER using python.
I wrote my python program as below.
import pyodbc
import subprocess
cnx = pyodbc.connect("DSN=myDSN;UID=myUID;PWD=myPassword;port=1433")
runcmd1 = subprocess.check_output(["usbrh", "-t"])[0:5]
runcmd2 = subprocess.check_output(["usbrh", "-h"])[0:5]
cursor = cnx.cursor()
cursor.execute("SELECT * FROM T_TABLE-A;")
cursor.execute('''
INSERT INTO T_TABLE-A (TEMP,RH,DATE,COMPNAME)
VALUES
(runcmd1,runcmd2,GETDATE(),'TEST_Py')
''')
cnx.commit()
Then get error like below.
# python inserttest.py
Traceback (most recent call last):
File "inserttest.py", line 13, in <module>
''')
pyodbc.ProgrammingError: ('42S22', "[42S22] [FreeTDS][SQL Server]Invalid column name 'runcmd1'. (207) (SQLExecDirectW)")
If I wrote like below, it's OK to insert.
import pyodbc
cnx = pyodbc.connect("DSN=myDSN;UID=myUID;PWD=myPassword;port=1433")
cursor = cnx.cursor()
cursor.execute("SELECT * FROM T_TABLE-A;")
cursor.execute('''
INSERT INTO T_TABLE-A (TEMP,RH,DATE,COMPNAME)
VALUES
(20.54,56.20,GETDATE(),'TEST_P')
''')
cnx.commit()
The command USBRH -t gets temperature and USBRH -h gets humidity. They work well in individual python program.
Does anyone have idea to solve this error?
Thanks a lot in advance.
check the data types returning from these two lines
runcmd1 = subprocess.check_output(["usbrh", "-t"])[0:5]
runcmd2 = subprocess.check_output(["usbrh", "-h"])[0:5]
runcmd1 and runcmd2 should be in 'double' data type since it accepts 20.54.
cursor.execute('''
INSERT INTO T_TABLE-A (TEMP,RH,DATE,COMPNAME)
VALUES
(runcmd1,runcmd2,GETDATE(),'TEST_Py')
''')
won't work because you are embedding the names of the Python variables, not their values. You need to do
sql = """\
INSERT INTO T_TABLE-A (TEMP,RH,DATE,COMPNAME)
VALUES
(?, ?, GETDATE(),'TEST_Py')
"""
cursor.execute(sql, runcmd1, runcmd2)

Syntax Error near "CHANGE" in sqlite3

I am attempting to execute the following (move a column to be the first one)
import sqlite3
db = sqlite3.connect('adatabase.sqlite')
c = db.cursor()
c.execute('ALTER TABLE tab1 CHANGE COLUMN r r def FIRST')
Unfortunately I get this error
Traceback (most recent call last):
File "<input>", line 1, in <module>
OperationalError: near "CHANGE": syntax error
What could be? Thanks in advance
SQLite does not support a CHANGE COLUMN feature; if any.
Only the RENAME TABLE and ADD COLUMN variants of the ALTER TABLE
command are supported
See all missing features: SQL Features That SQLite Does Not Implement

Python: Execute Stored Procedure with Parameters

I'm working on a Python script that writes records from a stored procedure to a text file. I'm having issues executing the stored procedure with parameters.
I'm not sure what I could do differently to execute this stored procedure with both parameters. You can see the error I'm getting below.
Any insight would be appreciated.
Here's my code
# Import Python ODBC module
import pyodbc
# Create connection
cnxn = pyodbc.connect(driver="{SQL Server}",server="<server>",database="<database>",uid="<username>",pwd="<password>")
cursor = cnxn.cursor()
# Execute stored procedure
storedProc = "exec database..stored_procedure('param1', 'param2')"
# Loop through records
for irow in cursor.execute(storedProc):
# Create a new text file for each ID
myfile = open('c:/Path/file_' + str(irow[0]) + '_' + irow[1] + '.txt', 'w')
# Write retrieved records to text file
myfile.write(irow[2])
# Close the file
myfile.close()
Here's the error
Traceback (most recent call lst):
File "C:\Path\script.py", line 12, in <module>
for irow in cursor.execute(storedProc):
pyodbc.ProgrammingError: ('42000', "[4200] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'param1'. <102> <SQLExecDirectW>">
I was able to fix the syntax error by removing the parenthesis from the query string.
# Execute stored procedure
storedProc = "exec database..stored_procedure('param1', 'param2')"
should be
# Execute stored procedure
storedProc = "exec database..stored_procedure 'param1','param2'"
This worked for me
query = "EXEC [store_proc_name] #param1='param1', #param2= 'param2'"
cursor.execute(query)
For SQL Server:
cursor.execute('{call your_sp (?)}',var_name)

python sqlite3 cursor.execute() with parameters leads to syntax error near ? (paramstyle qmark)

after searching untill madness, i decided to post a question here.
I try to create a sqlite3 database where i'd like to make use of the secure variable substituation function of the cursor.execute(SQL, param) function. My function goes like this:
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sqlite3
def create():
values = ("data")
sql = "CREATE TABLE IF NOT EXISTS ? ( name TEXT, street TEXT, time REAL, age INTEGER )"
con = sqlite3.connect("database.db")
c = con.cursor()
c.execute(sql, values)
con.commit()
c.close()
con.close()
if __name__ = "__main__":
create()
I know that the first argument should be the sql command in form of a string and the second argument must be a tuple of the values which are supposed to be substituted where the ? is in the sql string.
However, when i run the file it returns the following error:
$ ./test.py
Traceback (most recent call last):
File "./test.py", line 21, in <module>
create()
File "./test.py", line 14, in create
c.execute(sql, values)
sqlite3.OperationalError: near "?": syntax error
This also happens when paramstyle is set to named (e.g. the :table form).
I can't spot a syntax error here, so i think that the problem must be caused somewhere in the system. I tested it on an Archlinux and Debian install, both post me the same error.
Now it is up yo you, as I have no idea anymore where to look for the cause.
SQL parameters can only apply to insert data, not table names. That means parameters are not even parsed for DDL statements.
For that you'll have to use string formatting:
sql = "CREATE TABLE IF NOT EXISTS {} ( name TEXT, street TEXT, time REAL, age INTEGER )".format(*values)
As I understand, your parameter is the table name?
so your command would be
tbl = 'my_table'
sql = "CREATE TABLE IF NOT EXISTS '%s' ( name TEXT, street TEXT, time REAL, age INTEGER )" % tbl

SQLite error in Python

I have a simple piece of code to update a row in sqlite:
def UpdateElement(new_user,new_topic):
querycurs.execute('''INSERT into First_Data (topic) values(?) WHERE user = (?)''',([new_topic], [new_user]))
However, this gives me the error:
Traceback (most recent call last):
File "C:/Python27/Database.py", line 40, in <module>
UpdateElement("Abhishek Mitra","Particle Physics")
File "C:/Python27/Database.py", line 36, in UpdateElement
querycurs.execute('''INSERT into First_Data (topic) values(?) WHERE user = (?)''',([new_topic],[new_user]))
OperationalError: near "WHERE": syntax error
You should be using an UPDATE statement instead of INSERT:
def UpdateElement(new_user,new_topic):
querycurs.execute('''UPDATE First_Data
SET topic = ?
WHERE user = ?''', (new_topic, new_user))
The problem arises from the use of the parentheses and sending in new_user as an array, I believe. Values is an array, user is not.
You want something like:
cur.execute("UPDATE table SET value=? WHERE name=?", (myvalue, myname))
But yes, UPDATE sounds like what you wanted in the first place.

Categories