Inserting values from Python into SQL Server - python

I want to insert values into a SQL Server table, from Python.
Here is my table in SQL Server:
CREATE TABLE DB.type.[Ref]
(
[Type_Ref] varchar(65),
[ID_match] varchar(65),
[Data] varchar(65)
PRIMARY KEY ([Type_Ref], [ID_match])
)
To insert values from python I wrote this code:
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=????;'
'Database=DB;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
sql = "INSERT INTO DB.Ref (Type_Ref, ID_match, Data) VALUES (?, ?, ?)"
cursor.execute(sql, (DATA[Type_Ref], DATA[ID_match], DATA[Data]))
conn.commit()
cursor.close()
conn.close()
However, when I run Python, I don't see any rows of data in SQL Server...
I noticed my IDE is giving this, after I run the python code above:
Process finished with exit code -1073741819 (0xC0000005)
Solution: I solved this problem by deleting the table in sql-server and create a new one.

I think you are not building your conn object correctly. When I try to match your pattern, I receive a TypeError. Try this instead:
server='server'
database='database'
user='username'
password='secret'
conn = pyodbc.connect(
server=server,
database=database,
user=username,
password=password,
port=1433,
driver='ODBC Driver 17 for SQL Server'
)
The rest of your code looks like it should work fine.

try the following:
Columns = ['Type_Ref', 'ID_match', 'Data']
sql = "INSERT INTO dbo.Ref([Type_Ref], [ID_match], [Data]) VALUES (?,?,?)"
cursor.executemany(sql, DATA[Columns].values.tolist())
conn.commit()

Thaks for the help, I solved this problem by deleting the table in sql-server and create a new one.

Related

psycopg2 with Postgres fetchall works but not execute

I am trying to execute some Postgres queries with psycopg2.
import psycopg2
conn = psycopg2.connect(
host="test.postgres.database.azure.com",
database="postgres",
user="test",
password="test")
cur = conn.cursor()
sql = "select site_panel from test.ws_sites"
cur.execute(sql)
rows = cur.fetchall()
The query above works well and returns the data but the following query does not delete the table as intended.
cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
Anything wrong I'm doing here?
A query that modifies table data or schema structure needs to be committed:
cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
conn.commit()
Alternatively, place
conn.autocommit = True
after creating the connection.

Mysql cursor is not fetching any data

I want to make one SELECT query from python to mysql DB.
But I'm getting an empty list when I call cursor.fetchall()
I have already tested the connection and the query with DBeaver, and it works fine.
I tried following the tutorials on https://dev.mysql.com but didn work.
Here is my function:
import mysql.connector
from mysql.connector import connect
def execute_query_2(self,query):
connection = connect(
host="config.host",
database="config.db_name",
user="config.db_user",
password="config.db_user"
)
print(connection)
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
print(result)
for row in result:
print(row)
The print(connection) gives me mysql.connector.connection_cext.CMySQLConnection object at 0x7f6a725bfca0.
Also the query is being loaded successfully as 'SELECT * from occUserManager.addressInformation'.
The result for this should bring 44 rows.
Any help is more than welcome.

How to update a table in SQL Server during runtime using bind variable with a placeholder like '?' in python using pyodbc module?

I am writing a function which would save the records updated in the GUI which is made using Tkinter
def save():
conn = pyodbc.connect('Driver={SQL Server};'
'Server=XXXXXXX;'
'Trusted_Connection=yes;')
After connecting to the server,`I am getting values from another function, and updating into my database here,but I am getting an error.
cursor = conn.cursor()
record_id = select_box.get()
cursor.execute("UPDATE homeaddresses SET (?,?,?,?,?,?) where id=id)",
f_name_editor.get(),
l_name_editor.get(),
address_editor.get(),
city_editor.get(),
state_editor.get(),
pincode_editor.get())
conn.commit()
conn.close()
Should be something like
cursor.execute("UPDATE homeaddresses SET f_name=?,l_name,address=?,city=?,state=?,pincode=? where id=?",
f_name_editor.get(),
l_name_editor.get(),
address_editor.get(),
city_editor.get(),
state_editor.get(),
pincode_editor.get(),
record_id )

Why I receive error pyodbc.Error: ('HY000', 'The driver did not supply an error!')

I don't understand? Why I receve error: 'HY000', 'The driver did not supply an error!When I insert date time? But when I insert Null all is work. Please help me with it.
My code:
now=now.strftime('%Y-%m-%d %H:%M:%S')
connect = pyodbc.connect("DRIVER={SQL Server};Server=Study;Database=test;Trusted_Connection=yes;", autocommit=False)
cursor=connect.cursor()
cursor.execute("""
use base_for_time insert table_for_time_and_count values (Null,'"""+now+"""',Null,Null,Null)""")
connect.commit()
connect.close()
This might useful.
I think the issue is in your query and in your connection.
update connection:
connect = pyodbc.connect("DRIVER={SQL Server};SERVER=*****;UID=****;PWD=****;TRUSTED_CONNECTION=yes;", autocommit=False)
you're using executing multiple SQL statements in your single execution.
execute your statements one by one or use semicolon(;) instead between two queries.
cursor.execute("use db_name; insert into table_name values (val1,val2,..,valn);")

Function sequence error in PYODBC

I am using pyodbc to connect to a database and extract certain data from it.
Here is my code:
con = pyodbc.connect("driver={SQL Server};server= MyServer;database= MyDatabase;trusted_connection=true")
cursor = con.cursor()
SQL_command = """
SELECT RowID = ISNULL
(
(
SELECT TOP 1 RowID
FROM [MyDatabase].[admin].[MyTable]
WHERE [queue] = ? and processed IS NULL
)
,-1
)
"""
cursor.execute(SQL_command, queueNumber)
cursor.commit()
con.commit()
result_set = cursor.fetchall()
And I got following error after I run above code:
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server
Driver]Function sequence error (0) (SQLFetch)')
May I know what caused such problem, and how can I fix it?
Thanks.
I believe your problem is the strange commit statements. You only need to commit when inserting or updating records not selecting.
cursor.execute(SQL_command, queueNumber)
result_set = cursor.fetchall()
Also, in the future when using commit, both cursor.commit and con.commit do the same thing, you only need one.
Finally, I'd get used to calling execute with the second arguement as a tuple:
cursor.execute(SQL_command, (queueNumber,))
The way you have it works for pyodbc but is not DB API standard.
I was recieving the two following errors more or less interchangeably:
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC Driver 17 for SQL Server]Function sequence error (0) (SQLGetData)')
pyodbc.Error: ('HY007', '[HY007] [Microsoft][ODBC Driver 17 for SQL Server]Associated statement is not prepared (0) (SQLNumResultCols)')
My problem was, that two threads were using the same connection, which led to weird states of the prepared statements. I fixed it by creating a new connection for each thread.

Categories