SQL insert works in Oracle SQL Developer, but not in python - python

I have what would appear to be a straight forward insert statement for Oracle SQL. It works properly in Oracle SQL Developer but the same command will not work in Python, complaining about
cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended.
This happens on the line for the cursor.execute() call. The query itself is:
insert into TestNamesTable (TestName, TheUser, TheProject) values ('mytest.s', 'bjurasz', 'Beta');
If run in SQL Developer I get a new row. Inside Python I get the termination error. From what I can tell its properly formed and terminated.
Here is how I construct the query in python:
sql = "insert into TestNamesTable (TestName, TheUser, TheProject) values ('%s', '%s', '%s');" % (diagname, username, project)
print sql
cursor.execute(sql)
connection.commit()

Try this:
# These are just random definitions, must be of type table requires
diagname = "DEFINE HERE"
username = "SOMEBODY"
project = "PROJECT NAME"
# Assuming you've defined your connection before
cursor.execute("""insert into TestNamesTable (TestName, TheUser, TheProject) values (:diagname, :username, :project)""",
{"diagname": diagname, #cx_Oracle likes this bind-variable looking syntax
"username": username.
"project": project})
connection.commit()

Related

How to commit stored procedure execution by using pyodbc

I am trying to execute stored procedure by using pyodbc in databricks, after executing SP I tried to commit the connection but, commit is not happening. Here I am giving my code, please help me out from this issue.
import pyodbc
#### Connecting Azure SQL
def db_connection():
try:
username = "starsusername"
password = "password-db"
server = "server-name"
database_name = "db-name2"
port = "db-port"
conn=pyodbc.connect('Driver={ODBC Driver 17 for SQL server};SERVER=tcp:'+server+','+port+';DATABASE='+ database_name +';UID='+ username +';PWD='+ password)
cursor=conn.cursor()
return cursor, conn
except Exception as e:
print("Faild to Connect AZURE SQL: \n"+str(e))
cursor, conn = db_connection()
# conn1.autocommit=True
cursor.execute("delete from db.table_name")
cursor.execute("insert into db.table_name(BUSINESS_DATE) values('2021-10-02')")
cursor.execute("exec db.SP_NAME '20211023'")
conn.commit()
conn.close()
here I am commiting connection after SP excution. deletion and insertion is not happening at all. and I tried with cursor.execute("SET NOCOUNT ON; exec db.SP_NAME '20211023'") but it's also not working.
Thanks in Advance
If you check this document on pyodbc, you will find that -
To call a stored procedure right now, pass the call to the execute method using either a format your database recognizes or using the ODBC call escape format. The ODBC driver will then reformat the call for you to match the given database.
Note that after connection is set up or done, try doing conn.autocommit = True before calling your SP and it will help. By default it is false.
Executing the Stored Procedure.
You will be able to execute your stored procedure if you follow the below code snippet.
cursor = conn.cursor()
conn.autocommit = True
executesp = """EXEC yourstoredprocedure """
cursor.execute(executesp)
conn.commit()
Delete the Records in SQL Server
You can delete record as shown in the below example.
...#just an example
cursor.execute('''
DELETE FROM product
WHERE product_id in (5,6)
''')
conn.commit()
Don’t forget to add conn.commit() at the end of the code, to ensure that the command would get executed.
Insert record in SQL Server
The below snippet show how we can do the same.
...#just an example
cursor.execute("INSERT INTO EMP (EMPNO, ENAME, JOB, MGR) VALUES (535, 'Scott', 'Manager', 545)")
conn.commit()
I will suggest you to read the for following document for more information.
Delete Record Documentation.
Insert Record Document

Python SQL Script - How to send email with error

I've built a Python script that runs a report for me using one of our vendor's API's, then uploads the data directly to an MS SQL server. I would like to add an error handler that sends an email when the insert fails for any reason.
Can I just wrap my insert statement in a try? Currently I have this going to a local server for testing...
conn = pyodbc.connect('Driver={SQL Server};'
'Server=localhost\*****local;'
'Database=Reporting;'
'Trusted_Connection=yes;')
#Set cursor variable
cursor = conn.cursor()
executeValue = """INSERT INTO New_Five9_CallLog
(Call_ID, [Timestamp],
Campaign, Call_Type, Agent_Email, Agent_Name, Disposition,
ANI, Customer_Name, DNIS, Call_Time, Rounded_Bill_Time,
Cost, IVR_Time, Queue_Wait_Time, QCB_Wait_Time,
Total_Queue_Time, Ring_Time, Talk_Time, Hold_Time, Park_Time,
ACW_Time, Transfers, Conferences, Holds, Parks, Abandoned,
Recordings, Handle_Time, Session_ID, IVR_Path,
Skill, Ticket_Number)
VALUES (""" + values + ")"
#Execute query
cursor.execute(executeValue)
#Commit and close
conn.commit()
conn.close()
I get the values variable with some other script above this section. What I'd like to know is how to capture an error on this section and then send an email to myself with the error description.
Check out this answer https://stackoverflow.com/a/42143703/1525867 explaining how to catch pyodbc specific errors (I personally use https://sendgrid.com/ to send emails)

Updating SQL table using mysql python module

I am attempting to update a single value in a single cell in a SQL table using the mysql connector for python. Using the following code, I get no error messages, but nor does the table actually update. The value of the cell that I am attempting to update is sometimes empty, sometimes NULL, and sometimes contains a string. Here is my code:
query = ("UPDATE data_set SET %s = '%s' WHERE id = %s") % (column_to_change, change_to_value, row_id)
What am I doing wrong?
Edit: Thanks for the replies so far. I do not think there is any functional issue with the surrounding code (outside of the vulnerability to SQL injection, which I have fixed, here and elsewhere), as I have been effective executing similar code with different queries. Here is my code now:
column_to_change = "column2"
change_to_value = "james"
id = "1234"
cnx = mysql.connector.connect(user='user', password='password',
host='db.website.com',
database='database')
cursor = cnx.cursor()
query = ("UPDATE data_set SET %s = %s WHERE policy_key = %s")
cursor.execute(query, (column_to_change, change_to_value, id))
cursor.close()
cnx.close()
If it's relevant, it turns out the cells I'm trying to insert into are formatted as VARCHAR(45). When I run a SELECT query on a cell, it returns a name formatted like: (u'James',)
If I set change_to_value = "(u'James',)", I receive the following error message:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntac; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''column1' = '(u\'James\',)' WHERE id = '1234'' at line 1
Make sure you are following all the steps:
conn = pyodbc.connect("SERVER=my.server;DATABASE=my_database;UID=my_user;PWD=my_password;",ansi=True)
cursor = conn.cursor()
query = ("UPDATE data_set SET %s = '%s' WHERE id = %s") % (column_to_change, change_to_value, row_id)
cursor.execute(query)
And also verify the SQL query that your passing to .execute() is same as that you want to run on your database
Depending on your version of Python, perhaps it is an issue with your string interpolation. Otherwise, you may not be connecting your cursor and executing the query successfully. I am assuming you are executing your query elsewhere in your code, but in the instance you are not, this should work:
cursor.execute ("""
UPDATE data_set
SET %s=%s
WHERE id=%s
""", (column_to_change, change_to_value, row_id))
Alternatively, you could store this query in a variable as you have done, assign the respective variables and execute afterward like so:
query = (“UPDATE data_set SET %s=%s WHERE id=%s”)
column_to_change = [YOUR ASSIGNMENT HERE]
change_to_value = [YOUR ASSIGNMENT HERE--if this is a string, it should be formatted as such here]
row_id = [YOUR ASSIGNMENT HERE]
cursor.execute(query, (column_to_change, change_to_value, row_id))
Basic string interpolation is prone to SQL injection and should be avoided.
For more reference, see here

Can't upload Images to MS Sql server via pyodbc

i'm trying to upload an image to MS SQL web-server in Linux(raspbian) environment using python language. so far i had able connect to MS Sql and also i had create a table. And im using pyodbc.
#! /user/bin/env python
import pyodbc
dsn = 'nicedcn'
user = myid
password = mypass
database = myDB
con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (dsn, user, password, database)
cnxn = pyodbc.connect(con_string)
cursor = cnxn.cursor()
string = "CREATE TABLE Database1([image name] varchar(20), [image] varbinary(max))"
cursor.execute(string)
cnxn.commit()
this part complied without any error. that means i have successfully created a table isn't? or is there any issue?
i try to upload image as this way.
with open('new1.jpg','rb') as f:
bindata = f.read()
cursor.execute("insert into Database1(image name, image) values (?,?)", 'new1', bindata)
cnxn.commit()
i get the error on this part. and it pyodbc.ProgrammingError: ('42000', '[42000] [FreeTDS] [SQL Server] Satement(s) could not be prepared. (8180) (SQLParamData)')
can some one help me please. thank you
Your parameters must be passed in as one sequence, not as two separate arguments. A tuple will do nicely here:
cursor.execute(
"insert into Database1([image name], image) values (?,?)",
('new1', pyodbc.Binary(bindata)))
Note that you also need to quote the image name column correctly, and wrap the data in a pyodbc.Binary() object; this will produce the right datatype for your Python version (bytearray or bytes).

MySQL in Python

The purpose is to check if the email already exists in the database utilizing python and MySQLdb. I am using the variable mail to store the e-mail. The MySQL form is email. I have the code below:
if cursor.execute("select count(*) from registrants where email = " + "'"email2"'") == 0:
print "it doesn't exist!"
What is wrong with this statement or how can I go about doing this?
I hardly know where to start.
Just typing a string of SQL into a Python program doesn't somehow query the database. You actually have to open a database connection, instantiate a cursor, use that cursor to run the SQL, and fetch the result. All this is explained in the MySQLdb documentation.
Once you've done that, you'll still need to actually pass the email parameter from your form to the SQL statement, which you're not doing either.
well that won't work because that's just the mysql query string. You have to execute this query using a mysql client receive the results and the test. Using pymysql would be something like this:
import pymysql
connection = pymysql.connect(host,user,password,database)
cursor = connection.cursor()
cursor.execute("select count(*) from registrants where email = ?") #you need to replace the ? with some actual value or the query will fail
result = cur.fetchone()
if result[0]==0:
print "E-mail does not exist!"

Categories

Resources