Python pyodbc 'execute only' - python

I am trying out the pyodbc to connect to a local MSSQL database with the code bellow:
import pyodbc
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=localhost;'
'Database=SampleDb;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute = ('SELECT * FROM SampleDb.dbo.flights')
for row in cursor:
print(row)
Getting the following error:
cursor.execute = ('SELECT * FROM SampleDb.dbo.flights')
AttributeError: 'pyodbc.Cursor' object attribute 'execute' is read-only

cursor.execute is a function, so you just need to call it and not to assign something to it. Try this:
cursor.execute('SELECT * FROM SampleDb.dbo.flights')
Sources:
pyodbc wiki

Related

How can we load data from a data frame to Azure SQL Server?

I am trying, for the first time ever, to send data from a data frame in Spyder to Azure SQL Server...I think it's called Synapse. I created a small table in the database and when I run the code below, I see the results I expect to see.
import pyodbc
server = 'ryan-server.database.windows.net'
database = 'ryan_sql_db'
username = 'UN'
password = 'PW'
driver= '{ODBC Driver 17 for SQL Server}'
with pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT * From Order_Table")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
So, the connection is fine. I guess I am just stuck on the syntax to push a data frame to SQL Server in Azure. I tested the code below.
import pyodbc
server = 'ryan-server.database.windows.net'
database = 'ryan_sql_db'
username = 'UN'
password = 'PW'
driver= '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
all_data.to_sql('health', conn, if_exists='replace', index=True)
When I run that code, I get this error.
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)")
Try to do it by importing Pandas and pyodbc.
Below are few basic steps which we follow usually:
Connect to SQL Server.
Install all your python packages in your local.
Load the data into CSV.
Later you can use below Python script to load it from dataframe.
import pyodbc
import pandas as pd
df = pd.read_csv("c:\\user\\username\department.csv")
server = 'yourservername'
database = 'AdventureWorks'
username = 'username'
password = 'yourpassword'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
#Insert Dataframe into SQL Server:
for index, row in df.iterrows():
cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
cnxn.commit()
cursor.close()
After completing the configs you can run below command to get the data from SQL:
SELECT count(*) from HumanResources.DepartmentTest;
Refer to this official doc for detailed explanation.

Connect python with SQL Server

I'm trying to load to the memory a table which is on a SQL Server database, but keep getting an error.
I coded:
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-VCIBA22\MS_SQL_SERVER;'
'Database=BikeStores;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM BikeStores.staffs')
and received the following error:
pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL
Server Driver][SQL Server]Invalid object name 'BikeStores.staffs'.
(208) (SQLExecDirectW)")
Any ideas?
Thanks!

Connecting to SQL Server Express 2017 via Python

I'm trying to connect to SQL Server 2017 Express via Python and tried the following code:
conn = pyodbc.connect('Driver={SQL Server};'
'Server=USYD1WCXS3\SQLEXPRESS;'
'Database= tempdb;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM db_name.tablename')
for row in cursor:
print(row)
I also tried the following:
conn = pyodbc.connect('Driver={SQL Server Native Client 17.0};'
'Server=USYD1WCXS3\SQLEXPRESS;'
'Database= tempdb;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM db_name.tablename')
for row in cursor:
print(row)
and
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=USYD1WCXS3\SQLEXPRESS;'
'Database= tempdb;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM db_name.tablename')
for row in cursor:
print(row)
This is the error I am getting every time
InterfaceError
Traceback (most recent call last)
in
1 import pyodbc
2 conn = pyodbc.connect('Driver={SQL Server Native Client 17.0};'
3 'Server=USYD1WCXS3\SQLEXPRESS;'
4 'Database= tempdb;'
5 'Trusted_Connection=yes;')
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

Unable to write to SQL Server even when using parameters

The SQL Server has these properties.
I want to write df to a SQL Server table but I get an error "table does not exist".
What am I doing wrong?
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-FCBC9GE/NEW_INSTANCE;'
'Database=master;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM df')

Python - Data for mysql with dataframe

I'm new to Python and I wanted to ask you for help.
I want to put the data of a view in SQL Server into a table of my database in MySQL, when I try to give the following error:
Execution failed on sql: SELECT name FROM sqlite_master WHERE
type='table' AND name=?; not all arguments converted during string
formatting unable to rollback
Using Python version 3.7
Below is the code I use:
import pymysql.cursors
import pyodbc
import pandas as pd
# SQL Server Connection
connection = pyodbc.connect("DSN=SQLServer") #autocommit=True
try:
with connection.cursor() as cursor:
result = "SELECT * FROM dw.dbo.vW_sale"
df = pd.read_sql_query("SELECT * FROM dw.dbo.vW_sale", connection)
cursor.execute(result)
table = cursor.fetchall()
print(table)
finally:
connection.close()
# MySQL connection
cnx = pymysql.connect(host='test',
user='test',
password='test',
db='dw')
try:
with cnx.cursor() as cursor:
mysql = "select *from ft_sale_test"
cursor.execute(mysql)
result = cursor.fetchall()
#print(result)
finally:
cnx.close()
# using if_exists to handle the table that already exists
The error happens right here
df.to_sql(con=cnx, name= 'ft_sale_test', if_exists= 'replace')

Categories

Resources