Connecting python 3.3 to microsoft sql server 2008 - python

I am new to python. I am using Pydev IDE with Eclipse for python programming in my Windows machine. I am using python 3.3 vern and want to connect with MS Sql Server 2008. Could someone suggest how should I connect with MS Sql Server 2008.

I will augment mata's answer with a pypyodbc example.
import pypyodbc
connection_string ='Driver={SQL Server Native Client 11.0};Server=<YOURSERVER>;Database=<YOURDATABASE>;Uid=<YOURUSER>;Pwd=<YOURPASSWORD>;'
connection = pypyodbc.connect(connection_string)
SQL = 'SELECT * FROM <YOURTABLE>'
cur = connection.cursor()
cur.execute(SQL)
cur.close()
connection.close()

pyodbc supports python3 and can connect to any databas for wich there's an odbc driver, including sql server.
There's also a pure python implementation pypyodbc which also should supoort python3.
adodbapi also claims to work with python3.
Here you can find a list with some more options.

import pyodbc
server = 'SERVIDORNOMEOUIP'
database = 'MEUBANCO'
username = 'USERSQL'
password = 'SENHASQL'
#for SQL Server 2008
driver='{SQL Server Native Client 10.0}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password + ';')
cursor = cnxn.cursor()
cursor.execute("SELECT nome,senha FROM [tabusuariosenha]")
row = cursor.fetchone()
print ("CAMPO1 | CAMPO2 " )
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()

Related

How to connect to Azure sql database through python anaconda jupyter

I am trying to connect to azure sql database through Jupyter notebook and later to load the data into excel/csv .I have the details of server and database only .Username & password i think by default its taking my desktop credentials(unsure).
Here is tried code
import pyodbc
cnxn = pyodbc.connect(Server=myserver;Database=mydatabase)
In order to connect to your Azure SQL database with your jupyter notebook use the following:
import pyodbc
server = 'tcp:SQLSERVER.database.windows.net' # Server example
database = '<INSERT DATABASE NAME>'
username = '<INSERT USERNAME>'
password = '<INSER PASSWORD>'
driver= '{ODBC Driver 17 for SQL Server}' # Driver example
connection= pyodbc.connect('DRIVER=' + driver + ';SERVER=' +server + ';PORT=1433;DATABASE=' + database +';UID=' + username + ';PWD=' + password)
cursor = connection.cursor() # Just something you can do
print(connection)
connection.close()
For more details you can refer to the following links:
Connect to Azure SQL Database using Python and Jupyter Notebook
Connect to Azure SQL Database in a Jupyter Notebook using Python
Quickstart: Use Python to query a database
You need to give username, password of the Azure SQL database in connextion. Below is the code to establish connection of Azure SQl database using python in Jupyter Notebook.
import pyodbc
# Establish the connection
server = 'xxxxx.database.windows.net'
database = 'xxx'
username = 'xxxx'
password = 'xxxx'
driver= '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect('DRIVER=' + driver + ';SERVER=' +
server + ';PORT=1433;DATABASE=' + database +
';UID=' + username + ';PWD=' + password)
print(conn)
conn.close()
Reference: Use Python to query a database - Azure SQL Database & SQL Managed Instance | Microsoft Learn

Python & MySQL mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query

I'm trying to use import mysql.connector to SELECT * from a table with ~1.9million rows in a remote database.
When I run the same query using the mysql cli client everything works just fine so I don't believe the issue is network or serverside. I've tried increasing connection_timeout to ridiculous numbers, but I still run into mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
Any ideas what to try next?
import mysql.connector
mydb = mysql.connector.connect(
host="mysql.prod.example.com",
user="user",
password="pass",
database="db",
auth_plugin='mysql_native_password',
connection_timeout=1000000
)
mycursor = mydb.cursor(dictionary=True)
mycursor.execute("SELECT * FROM table")
update_list = []
for row in mycursor:
row_id = row["id"]
row_ip = row["ip"]
print("IP: "+row_ip)
newlist = [row_id,row_ip,"/128"]
update_list.append(newlist)
Switching from Python2 to 3 solved my problem.
- #!/usr/bin/python
+ #!/usr/bin/python3

Azure Windows logins are not supported in this version of SQL Server while connecting sql server using python

Hi I'm using sql server V17.3 on Micorsoft Azure platform. I'm trying to upload data from python 3.7 data frame to my table test on sql server. So I wrote following code
import time
start_time = time.time()
import pyodbc
from sqlalchemy import create_engine
import urllib
dataToUpload=pd.read_csv("intermediate.csv")
params = urllib.parse.quote_plus(r'DRIVER=SQLServer};SERVER=nesbaexplsql001.database.windows.net;DATABASE=mydatabase;Trusted_Connection=False;Encrypt=True;uid=myuid;pwd=my password')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str)
dataToUpload.to_sql(name='test',con=engine, if_exists='append',index=False)
But I'm getting error message
DBAPIError: (pyodbc.Error) ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver][SQL Server]Windows logins are not supported in this version of SQL Server. (40607) (SQLDriverConnect); [HY000] [Microsoft][ODBC SQL Server Driver][SQL Server]Windows logins are not supported in this version of SQL Server. (40607)') (Background on this error at: http://sqlalche.me/e/dbapi)
While executing to_sql. I also tried by putting Trusted_Connection=yes & removing Encryption=True.But I got same error. Can you guide me to resolve this issue?
Please refer to my sample code:
import pyodbc
import csv
server = 'tcp:***.database.windows.net'
database = '***'
username = '***'
password = '***'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("select * from ***")
row = cursor.fetchone()
while row:
print(row[0])
row = cursor.fetchone()
mycsv = r'D:\insert.csv' # SET YOUR FILEPATH
with open (mycsv, 'r') as f:
reader = csv.reader(f)
columns = next(reader)
query = 'insert into <TABLE NAME>({0}) values ({1})'
query = query.format(','.join(columns), ','.join('?' * len(columns)))
cursor = cnxn.cursor()
for data in reader:
cursor.execute(query, data)
cursor.commit()
Add one piece to your connection string:
Integrated Security = False;
Hope this helps.

How to pass connection parameter "ApplicationIntent=ReadOnly" when using pymssql

I only have readonly access to a SQL Server db. How do I pass connection parameter "ApplicationIntent=ReadOnly" when using pymssql to connect to the database? If pymssql doesn't support it, is there any other python library that I can use?
The only way to configure readonly connection intent with pymssql seems to be to configure freetds on which it's based, but it did not work out for me. I've had to use pyodbc instead of pymssql
from pyodbc import connect
conn = connect(
'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + host + ';PORT=' + port + ';DATABASE='
+ database + ';UID=' + user + ';PWD=' + password + ';ApplicationIntent=ReadOnly')
Because pymssql is dependent on FreeTDS
You really need to address the connection parameters to your MS-SQL server used by FreeTDS
Because ApplicationIntent is listed in the freetds user guide as an option you should be able to use it.
pyodbc has a readonly parameter. For example:
import pyodbc
conn = pyodbc.connect(driver='{SQL Server}', host=Server, database=Database,
trusted_connection='yes', user='', password='', readonly = True)

Pyodbc: Unable to update table on database (no error)

I have:
import pyodbc
con_str = "DRIVER={%s};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s" % \
('FreeTDS','192.168.1.22','myuser','mypass','mydb')
con = pyodbc.connect(con_str)
cur = con.cursor()
cur.execute("update mytable set name='abcd'")
con.commit()
con.close()
The code executes and exits without any error !
But the database remains unchanged - nothing happened.
Resolved..
The problem was in the FreeTDS driver that I used.
I ran the same script on a windows machine using its native SQL Server Native Client 10.0 driver.
And it worked GREAT !

Categories