I have a SELECT statement in MySQL that fetches all the rows that matches a criteria as follows:
SELECT * FROM table_name WHERE sl_no=number;
and the table structure is as follows:
--------------------------
sl_no|val_1|val_2|val_3
---------------------------
1|a|b|c
2|d|e|f
3|g|h|i
----------------------------
One of the columns, val_1 is encrypted. I need to decrypt this column when the SELECT query above is executed. I know how to do it in MySQL as below:
SET #key_str = key;
SET block_encryption_mode=aes-256-ecb;
SELECT AES_DECRYPT(FROM_BASE64(val_1), #key_str) FROM table WHERE sl_no=number;
I want to replicate the same process in Python using MySQLdb. My attempts:
I first tried the answer mentioned in this question, which did not work
I then tried to run the commands shown above in Python itself the following way
database = MySQLdb.connect(host=host_name,user=databaseUsername,passwd=databasePassword,db=databaseName,cursorclass=MySQLdb.cursors.DictCursor)
set_query="SET #key_str=(%s)%config['key_str']"
set_block="SET block_encryption_mode=(%s)config['aes_mode']"
database.query(set_query)
database.query(set_block)
However, I keep getting the following error: _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near key_string at line 1"). for this line: set_query="SET #key_str=(%s)%config['key_str']
Related
I'm trying to implement the code on this video to my mysql database. When I enter the values by hand to python code it works. However when i use python dictionaries for getting entries from gui like the video it's says: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':b_name, :b_category, :b_status, :b_author)' at line 1
On video he uses SQLite this can be the problem but i'm not sure.
my code is here
# Insert Into Table
c.execute("INSERT INTO `books` (`bookName`, `bookCategory`, `BookCurrentStatus`, `bookAuthor`) VALUES (:b_name, :b_category, :b_status, :b_author)",
{
'b_name': b_name.get(),
'b_category': b_category.get(),
'b_status': b_status.get(),
'b_author': b_author.get()
})
MySQLdb only supports the format and pyformat parameter styles. The named parameter style used in the video isn't supported.
I believe that you are not actually doing string replacement with your current setup, try this:
# Insert Into Table
c.execute("INSERT INTO `books` (`bookName`, `bookCategory`, `BookCurrentStatus`, `bookAuthor`) VALUES ({b_name}, {b_category}, {b_status}, {b_author})",
{
'b_name': b_name.get(),
'b_category': b_category.get(),
'b_status': b_status.get(),
'b_author': b_author.get()
})
I'm trying to insert variables as data into a database
I'm using this (part of it)
query = "INSERT INTO table_name (name) VALUES (%S)"
aa="naam"
cursor.execute(query,aa)
and everytime, I get the following error message:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%S)' at line 1"
no matter what I try to do, I'm getting this message (put it in """, put () around it, ...)
Hope someone can help me
The format needs to be lowercase, so change the query into: query = "INSERT INTO table_name (name) VALUES (%s)".
I am trying to select some values within a table that has a column called "Name". That column contains tennis players names. I want to store some statistics for each player in python, but I am having trouble accessing the table. I keep getting a "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '='Rafael Nadal'' at line 1" As you can see, mysql clearly interprets the %s I had in place of 'Rafael Nadal' correctly, but it still brings up an error. Can anyone help me?
recordTuple = ('Rafael Nadal', )
mySql_insert_query = """SELECT `First_Serve(%)` FROM `serve2` WHERE Name =%s"""
cursor.execute(mySql_insert_query, recordTuple)
aI = cursor.fetchall()[0][0]/100
Since % is used to mark placeholders in the SQL, you have to double it if you want to use it literally.
mySql_insert_query = """SELECT `First_Serve(%%)` FROM `serve2` WHERE Name =%s"""
See How do I escape % from python mysql query
I am currently trying to use pyodbc to select data from a table within Database A and insert it into a table within Database B. I was able to establish connections with both databases, so I know there is no error there. Additionally, my first cursor.execute command (line #9) works as I was able to print all the data.
The issue I am running into is when I try and insert the data from the first cursor.execute command into Database B. There are a few questions on SO regarding this same error, however I have checked to ensure I am not committing on of those errors. All the data types are accepted within SQL Server, I have the correct number of parameters and parameter markers, and I have ensured that the columns within my Python code match both the input and output tables. I am completely stuck and would greatly appreciate any help.
The specific error I am getting is:
('HYC00', '[HYC00] [Microsoft][ODBC SQL Server Driver]Optional feature
not implemented (0) (SQLBindParameter)')
Please see my code below:
import pyodbc
import time
cnxn1 = pyodbc.connect(r"DRIVER={SQL Server Native Client 11.0};SERVER='Server';" + \
"DATABASE='DatabaseA';Trusted_Connection=Yes")
cursor1 = cnxn1.cursor()
cnxn2 = pyodbc.connect(r"DRIVER={SQL Server};SERVER='Server'," + \
"user='Username', password='Password', database='DatabaseB'")
cursor2 = cnxn2.cursor()
SQL = cursor1.execute("select * from table.DatabaseA")
SQL2 = """insert into table.DatabaseB([col1], [col2], [col3], [col4],[col5], [col6], [col7],
[col8], [col9], [col10], [col11], [col12], [col13], [col14],
[col15], [col16],[col17], [col18], [col19], [col20], [col21],
[col22], [col23], [col24], [col25], [col26], [col27], [col28],
[col29], [col30], [col31])
values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"""
for row in cursor1.fetchall():
cursor2.execute(SQL2,row)
In regard to the last two lines of code, I have also tried the following with no success:
for row in SQL:
cursor2.execute(SQL2,row)
I have a table named Container in mariadb having three fields container_id, mt_date and age.
What i am trying to do is, to update/set new values to the age field corresponding to the specific container_id, every time the db is loaded. I have kept the age and corresponding container_id in a python dictionary as a value and key, respectively. Than i loop through the dictionary and try to update age like this -
for i in list(age_dict):
frappe.db.sql("update Container set age = age_dict[i] where container_id = i")
Here, frappe.db.sql() is the db connecting command for my framework.
I am constantly getting this error message-
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[i] where container_id = i' at line 1")
I have checked my sql query code several times, but couldn't find the syntax error. Looking for help.
The python code you have inside your SQL statement is never interpreted. The database is literally trying to execute the command update Container set age = age_dict[i] where container_id = i which is indeed invalid syntax. You should use parameterization, which will help prevent SQL injection and will easily format the SQL command. The syntax is almost identical to string interpolation, but you pass the values (as a tuple) as a second parameter to frappe.db.sql().
for key in list(age_dict):
frappe.db.sql(
"update Container set age = %s where container_id = %s",
(age_dict[key], key)
)