I have an azure sql server instance containing a database which has a hyphen in its name like "database-name".
I am trying to connect via a python script and having some issues with it.
In the script when I use the connection string like this:
"Driver={ODBC Driver 18 for SQL Server};Server=serveraddress;Database=database-name;UID=username;PWD=password;"
I get the following error:
Incorrect syntax near 'name'.
I figured this may be caused by the hyphen and changed the connection string to this instead:
"Driver={ODBC Driver 18 for SQL Server};Server=serveraddress;Database=[database-name];UID=username;PWD=password;"
But I get an error like this:
Cannot open database "[database-name]" requested by the login. The login failed.
however I am able to login with the same user from SSMS.
Can this be permission related issue?
I tried to reproduce your scenario on my end and got results like the below:-
I created one Azure SQL server and database both with hyphen in their names like below:-
Make sure you add your client IP access to your Azure SQL database like below:-
I populated Azure SQL Database with one table and its entities.
Tried the below code to connect Azure SQL DB with python, Make sure your connection string format is correct as per the code below:-
You can validate the connection string from your Azure Portal like below:-
Code:-
import pyodbc
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=tcp:valley-server.database.windows.net,1433;'
'Database=valley-db;'
'Uid=siliconserver;'
'Pwd=xxxxxx#123')
cursor = conn.cursor()
cursor.execute('SELECT * FROM StudentReviews')
for i in cursor:
print(i)
cursor.close()
conn.close()
SQL command executed successfully by connecting to Azure-SQL DB. Make sure the ODBC package is installed in your machine from where you’re executing the code. And the server or Database name has correct spelling or syntax.
Related
I am using pyodbc for generating new tables in a remote SQL server. I wrote the following code, replacing column names, table names, driver name, and server name with dummy names.
import pyodbc
query="select columnA*2 where columnB!=0 from tableA into tableB"
connection = pyodbc.connect('Driver={driverA};''Server=serverA;'
'Trusted_Connection=yes;')
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
cursor.close()
connection.close()
I wonder when I run this this code in my Jupyter notebook (I am not sure if running it in a Jupyter Notebook is relevant, but I figure it doesn't hurt to mention it), does my laptop execute some parts of the code or does my laptop send all these code to serverA and ask serverA to execute the command?
What about the following code? Does my laptop simply send the code to the server and wait for the response? Alternatively, does my laptop asks for the entire tableA and then do some of the computing locally?
cnxn = pyodbc.connect("Driver= {driverA};" "Server=serverA;" "Database=databaseA;"
"Trusted_Connection=yes;")
diagramFinal = pd.read_sql("""select columnA*2 where columnB!=0 from tableA""", cnxn)
cnxn.close()
I read through this documentation without finding relevant information. So, I wonder if someone could help me with figuring it out.
I am new to programming and working on a self-motivated password analyzer project. Part of my program searches User's password through the common password list. Originally I had this folder as .txt file however I wanted to put the list in mySQL server. I was able to connect to my server and create a table with 3 rows that had passwords. However I can't figure out how to tell python to search through the sql server and the rows.
Thank you for the help!
So, since you're trying to fetch some data from MySQL, you need to initiate the connection with the MySQL server in the first place. Then you can perform your queries on the DB through Python.
To initiate connection
pip install mysql-connector-python. See Install MySQL Connector
Then you can import the connector in your script import mysql.connector.
Example
Updated as per the comments discussion.
from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='scott', password='password',
host='127.0.0.1', # Or 'localhost'
database='employees')
sql_select_query = "select * from passw"
cursor = cnx.cursor()
cursor.execute(sql_select_query)
records = cursor.fetchall()
for record in records:
password = record[0]
cnx.close()
Note: Consider using environment variables to securely use sensitive data (MySQL connection data).
More details with examples can be found in Connecting to MySQL Using Connector/Python.
I connecting to database on Azure using authentication ActiveDirectoryPassword.
ss
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+host+';UID='+user+';PWD='+password+';Authentication=ActiveDirectoryPassword')
It is working. The issue is that using this connection string I do not specify the DB. It just connecting me to master. How can I switch to DB I need. I have tried different connection strings (with database specified) but only this one works with ActiveDirectiryPassword.
You could try the below :
pyodbc.connect('DRIVER='+driver+';SERVER='+host+';DATABASE='+database+';UID='+user+';PWD='+password+';Authentication=ActiveDirectoryPassword')
I am Working on Ubuntu 18.04 when I am using Pyodbc connection with SQL Anywhere 17 Driver to connect to a Sybase DB, while trying to establish connection my Jupyter notebook Dies.
The expectation is, I should be able to run this code in Ubunt and connect to a Sybase DB.
I can connect and run query from Windows without problems(using DSN).
I have been working with other driver and SQL Server, MySQL and MariaDB and I have not encountered any problems.
I believe connection to Sybase database needs SQLANYWHERE DRVIER.
If Someone knows how get the connection string which is passed from pyodbc to the server when I use a DSN?(maybe this could give me an idea to know what i'm doing wrong).
Some advice?
Code run in windows without problems
import pyodbc
import pandas as pd
cnxn = pyodbc.connect("DSN=RevDSN")
print(cnxn)
data = pd.DataFrame(pd.read_sql_query(query, cnxn))
cnxn.close()
Since I didn't find a good explanation I am putting this here.
I installed the client from
https://archive.sap.com/documents/docs/DOC-35857
then followed the basic instructions from
https://wiki.scn.sap.com/wiki/display/SQLANY/Installing+SQL+Anywhere+17+on+Ubuntu+14.04
The ODBC Client will not ask for the keys
As the documentation says the important part is running the sa_config.sh and making sure that the exports happen.
Lastly edit the /etc/odbcinst.ini file and add the driver.
For example
[SQL Anywhere 17]
Driver=/opt/sqlanywhere17/lib64/libdbodbc17.so
TDS_Version=5.0
UsageCount=1
Then I used this connection string
import pyodbc
cnxn = pyodbc.connect('Driver={SQL Anywhere 17};LINKS=TCPIP{HOST=<server ip here>};PORT=2638;UID=admin;PWD=<password here>;ENG=<engine name>;DBN=<database name>;')
cursor = cnxn.cursor()
cursor.execute("select top 10 * from dba.<table name>")
for row in cursor:
print(row)
And it worked.
I have to send multiple data through Python from a DB allocated in the client to the Main DB in the server, whats the best solution to this? i currently have my web server up and functioning, i can fill my DB locally but i dont really know how to do it remotely, im using Python in my hardware, here is what i have so far in the client:
import mysql.connector
cnx = mysql.connector.connect(user='user', password='pass', host='url?', database='db') #im able to enter with this
cursor = cnx.cursor()
query = ("INSERT INTO IGNORE table " "(id,date,son) " "VALUES( (%s,%s,%s)")
for row in data: #ive already extracted data from the other DB
cursor.execute(query, (row[0],row[1],row[2]))
wich yealds an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the righ syntax to use near 'IGNORE table(id,date,son) VALUES (number, '2017-11-09 14:33:15', 18.987)' at line 1
One possibility - Make sure your mysqld service is binding to your external ip address (set in your mysql config file on the server). By default I believe it binds to 127.0.0.1 or localhost. If it is binding to localhost, your db will never respond to external requests.
I fixed the issue with the MySQL port in the following way: I opened the port internally from my VM instead of from my Virtual Network (I'm using the Google Cloud Platform).