create SQL table from existing table using pyodbc/turbodc in python - python

I would like to create a SQL table from an existing table. I'm using the turbodbc module (which is very similar to pyodbc).
# connect to database
conn = turbodbc.connect(connection_string="my_connection_string")
cursor = conn.cursor()
# execute SQL code
cursor.execute((" create table Test_Puts as"
" select * from OptionValue"
" where call_put = 'P'"))
However, I get the error message:
ODBC error
state: 42000
native error code: 156
message: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'select'.

Try to use this syntax:
select * into Test_Puts from OptionValue where call_put = 'P'
So, instead of this:
" create table Test_Puts as"
" select * from OptionValue"
" where call_put = 'P'"
use this:
" select * into Test_Puts"
" from OptionValue"
" where call_put = 'P'"

Related

pyodbc not recognising parameter placeholder in multi-line string

Why is pyodbc throwing this error:
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')
When I do have a parameter marker in the query?
It seems it only complains when I use a multiline string in python.
i.e. this is causing an error:
sql = """
SELECT a.r_object_id, a.object_name, a.document_status, a.document_id, a.document_status, b.r_version_label, a.r_link_cnt
from pharma_document_sp a, pharma_document_rp b where a.r_object_id = b.r_object_id and b.r_version_label = 'LATEST APPROVED' and a.document_id = ?
"""
cursor_cara.execute(sql, doc_id)
But this is OK:
sql = "SELECT a.r_object_id, a.object_name, a.document_status, a.document_id, a.document_status, b.r_version_label, a.r_link_cnt "
sql = sql + " from pharma_document_sp a, pharma_document_rp b where a.r_object_id = b.r_object_id and b.r_version_label = 'LATEST APPROVED' and a.document_id = ?"
cursor_cara.execute(sql, doc_id)
I am using:
pyodbc version 4.0.27, SQL ODBC Server Driver 17, Python 3.7.4

SQLAlchemy Text Parameter Binding gives '?'

I'm using ODBC Driver 17 for SQL Server
I have this:
q = text('select top 10 * from :x')
conn.execute(q, x="mytable")
which fails returning:
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Must declare the table variable "#P1". (1087) (SQLExecDirectW)')
[SQL: select top 10 * from ?]
[parameters: ('mytable',)]
Running q = test('select top 10 * from mytable') works however.
I'm at a lost as I've tried bindparams.
Martijin's comment is correct. The bind parameters only work for data.
q = text('select top 10 * from :x')
conn.execute(q, x="mytable")
is invalid.
But this,
q = text('select :x from mytable')
conn.execute(q, x="thing1")
works.

sqlite3.OperationalError: near "%": syntax error?

I'm receiving the error: sqlite3.OperationalError: near "%": syntax error
when I try to run the following code.
import sqlite3
def getFromDB(DBname,table, url):
conn = sqlite3.connect(DBname)
cursor = conn.cursor()
sql = '''SELECT * FROM %s WHERE URL=%s'''
stuff = cursor.execute(sql, (table,url))
stuff = stuff.fetchall()
return stuff
url = 'http://www.examplesite.com/'
getFromDB('AuthorData.sqlite','forbes',url)
I'm using parameters in my SQL query using %s. Thanks for the help!
Some idea:
- Using parameter is not available for table name
- Using string format is not good because of sql-injection
So first, create a method to make table name safe:
def escape_table_name(table):
return '"%s"'.format(table.replace('"', '')
Then complete the code with escape table name and parameter using ? for parameter:
sql = '''SELECT * FROM %s WHERE URL=?'''.format(escape_table_name(table))
stuff = cursor.execute(sql, (url,))
stuff = stuff.fetchall()
You can use :
sql = '''SELECT * FROM {0} WHERE URL= {1}'''.format(table, url)

Passing a folder location as an SQL parameter in python causes an error

I am fairly new to python and the only SQL I know is from this project so forgive the lack of technical knowledge:
def importFolder(self):
user = getuser()
filename = askopenfilename(title = "Choose an image from the folder to import", initialdir='C:/Users/%s' % user)
for i in range (0,len(filename) - 1):
if filename[-i] == "/":
folderLocation = filename[:len(filename) - i]
break
cnxn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\Public\dbsDetectorBookingSystem.accdb')
cursor = cnxn.cursor()
cursor.execute("SELECT * FROM tblRuns")
cursor.execute("insert into tblRuns(RunID,RunFilePath,TotalAlphaCount,TotalBetaCount,TotalGammaCount) values (%s,%s,0,0,0)" %(str(self.runsCount + 1), folderLocation))
cnxn.commit()
self.runsCount = cursor.rowcount
rowString = str(self.runsCount) + " " + folderLocation + " " + str(0) + " " + str(0) + " " + str(0) + " " + str(0)
self.runsTreeView.insert("","end", text = "", values = (rowString))
That is one routine from my current program meant to create a new record which is mostly empty apart from an index and a file location. This location needs to be saved as a string however when it is passed as a paramenter to the SQL string the following error occurs:
cursor.execute("insert into tblRuns(RunID,RunFilePath,TotalAlphaCount,TotalBetaCount,TotalGammaCount) values (%s,%s,0,0,0)" %(str(self.runsCount + 1), folderLocation))
ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'C:/Users/Jacob/Documents/USB backup'. (-3100) (SQLExecDirectW)") I assume this is because the SQL recognises a file path and wantsto user it. Does anybody know how to fix this?
You're not using the db-api correctly. Instead of using string formatting to pass your query params - which is error-prone (as you just noticed) AND a security issue, you want to pass them as arguments to cursor.execute(), ie:
sql = "insert into tblRuns(RunID, RunFilePath, TotalAlphaCount, TotalBetaCount, TotalGammaCount) values (%s, %s, 0, 0, 0)"
cursor.execute(sql, (self.runsCount + 1, folderLocation))
Note that we DONT use string formatting here (no "%" between sql and the params)
NB : note that the placeholder for parameterized queries depends on your db connector. python-MySQLdb uses % but your one may use a ? or anything else.
wrt/ your exact problem: since you didn't put quotes around your placeholders, the sql query you send looks something like:
"insert into tblRuns(
RunID, RunFilePath,
TotalAlphaCount, TotalBetaCount, TotalGammaCount
)
values (1,/path/to/folder,0,0,0)"
Which cannot work, obviously (it needs quotes around /path/to/folder to be valid SQL).
By passing query parameters the right way, your db connector will take care of all the quoting and escaping.

Can't get my SQL to display my score in my database form my pygame

I have tried to create a piece of code so when my game is over or the play wins he score is displayed in the database.
Game Code:
def gameover():
message = Msg("Game Over")
message.update()
player.kill()
shot.kill()
SQL = 'INSERT INTO TblScore(Score) VALUES (' + str(score.value)
Databaseconnector.INSERT(SQL)
Database Connection Code:
def INSERT(SQL):
print(SQL)
cursor.execute(SQL)
conn.commit()
Error:
ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement. (-3502) (SQLExecDirectW)')
You forgot the closing bracket:
SQL = 'INSERT INTO TblScore(Score) VALUES (' + str(score.value) + ')'
^^^^^^^

Categories

Resources