"Unclosed quotation mark" when connecting with pypyodbc - python

I've the following piece of code in Python, to connect to SQL Server but it always fails, even though the same from sqlcmd works.
Any ideas?
import pypyodbc
conn = pypyodbc.connect(DRIVER='{SQL Server}',Trusted_Connection='yes',server='sqldev\dwmaster',DATABASE='risk')
cur = conn.cursor()
The error I'm getting is:
pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver
][SQL Server]Unclosed quotation mark after the character string ' '.")

Fixed the error, doing the following.
conn = pypyodbc.connect("DRIVER={SQL Server};server='sqldev\\master',Database='risk',TrustedConnection=yes")
cur = conn.cursor()

Related

SQL python Connection issue

I am trying to pull data from SQL server, I am able to pull the sample data ( up to top 1000 records) but when I run it for all records I get following error:
('01000', '[01000] [Microsoft][ODBC SQL Server
Driver][DBNETLIB]ConnectionWrite (send()). (10054) (SQLGetData);
[01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]General network
error. Check your network documentation. (11)')
I am using following syntax
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=g8w00761s.inc.hpicorp.net;'
'Database=ContraDigital2.0;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
sql_query = pd.read_sql_query("""SELECT top 1000 * FROM [ContraDigital2.0].[dbo].[contra_anomaly_upfront_backend_1]""",conn)
print(sql_query)

How to resolve error when connecting to MS-SQL database via linux using pyodbc

I am trying to connect to external MS SQL database server from our Linux server using pyodbc and I am getting error.
Code:
import pyodbc
server = 'XXXXXXXXX,port'
database = 'XXXXXXXXXXXXXXX'
username = 'XXXXXXXXXXXX'
password = 'XXXXXXXX'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
#Sample select query
cursor.execute("SELECT ##version;")
row = cursor.fetchone()
while row:
print(row[0])
row = cursor.fetchone()
cnxn.close()
Error:
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot open database "xxxxxxxxxx" requested by the login. The login failed. (4060) (SQLDriverConnect)')
I also tried reading multiple solutions and trying them for example:
putting password in brackets like --> password = '{XXXXXXXX}' becuase it had special characters.
Also tried giving server as --> server = 'tcp:XXXXXXXXX,port' nothing worked it all gives me same error.
Could you please guide me resolve this issue.
Many thanks for your help.

Pyodbc connection to SQL Server failed - neither DSN nor SERVER keyword supplied

I am trying to make an insertion to my SQL Server database by using pyodbc. But I can never achieve it. Please help me.
By the way; I defined index_pred_as_int in previous code snippet.
My code:
import pyodbc
server = 'DESKTOP-T7OFQV6\SQLEXPRESS1'
database = 'VidgaEmotionRecognition'
#defining connection string
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; \\\
SERVER=' + server + '; \\\
DATABASE=' + database +';\\\
Trusted_Connection=yes;')
#creating the connection cursor
cursor = cnxn.cursor()
#defining insert query
insert_query='''INSERT INTO FaceEmotion (emotion)
VALUES (?);'''
#defining insertion value
values = index_pred_as_int
#insert the data
cursor.execute(insert_query, values)
#commit the insertion
cnxn.commit()
#grab the database table values
cursor.execute('SELECT * FROM FaceEmotion')
#printing the results
for values in cursor:
print(values)
And here's the error:
OperationalError
Traceback (most recent call last)
in
18 #defining connection string
---> 19 cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; \\
20 SERVER=' + server + '; \\
21 DATABASE=' + database +';\\
OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)')
I'm not sure I understand how the \\\ are supposed to work, but I think they are breaking it. I set up a similar connection on my computer and used your same connection string and got the same error. When I put the whole connection string on one line, it seems to work just fine.
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database +';Trusted_Connection=yes')
Edit: it also appears to work just fine if you use just one \ to divide your line, instead of that triple.

How to put pandas DataFrame using pyodbc in SQL Server Management Studio

With the pandas DataFrame called 'data' (see code), I want to put it into a table in SQL Server. How should I do this?
I read something on the internet with data.to_sql, so I tried a little with this function. However, it gives me an error message (see error message). It probably has to do with the argument con = conn. I don't know how to fix this. The error message says something about SQLite. I am not very advanced in using SQL, so I do not understand all errors.
Do you have any ideas? I think the conn is the only problem. The rest works fine.
Using SQL Server Management Studio 2018.
Ty in advance.
Error message:
Exception has occurred: DatabaseError
Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;':
('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]
Invalid object name 'sqlite_master'. (208) (SQLExecDirectW);
[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]
Statement(s) could not be prepared. (8180)")
def connection():
try:
#connect to network database
conn = None
conn = db.connect('Driver={SQL Server};'
'Server=xxsql.database.windows.net;'
'Database=xx;'
'uid=xx;'
'pwd=xx;')
#if connected do
if conn is not None:
print("The connection is established")
sql_query = 'select top 20 * from xx'
#read table into dataframe
#make a dataframe with records from table
dfObj = pd.read_sql_query(sql_query, conn)
#inspect result
print(dfObj)
#read into list
cursor = conn.cursor()
cursor.execute(sql_query)
#put cursor to list
cursor_list = list(cursor.fetchall())
#make copy so that we wont change original data
table = cursor_list.copy()
bibliography = Extract(table)
data = pd.DataFrame(bibliography)
#convert it to SQL
data.to_sql('ExtractedBib', con = conn, if_exists = 'append') #????
except db.Error as e:
print(e)
finally:
if conn is not None:
cursor.close()
conn.close()
print("The connection is closed")
else:
print("No connection established")
def main():
connection()
main()
Try using sqlalchemy instead.
import sqlalchemy
engine = sqlalchemy.create_engine(
"xxsql+pyodbc://uid:pwd#Server/Database",
echo=False)
...
data.to_sql('ExtractedBib', con=engine, if_exists = 'append')
Just change the template values into your database values (uid, pwd etc.)

Executing SQL Server Query in Python

I have connected SQL Server with Python using pyodbc module. The script seems to have run correctly, however, I am getting errors when I try to execute my SQL statement.
This is what I have done:
import pandas
import numpy
import pyodbc
conn = pyodbc.connect(
'Driver={SQL Server};'
'Server=test\SQLEXPRESS;'
'Database=test1;'
'Trusted_Connection=yes;'
)
cursor = conn.cursor()
def read(conn):
print("Read")
cursor = conn.cursor()
cursor.execute("select * from table")
for row in cursor:
print(f'row = {row}')
print()
read(conn) #to execute
I am wanting to execute a query that I would normally run within my SQL Server, but in Python:
SELECT * FROM table
This is the error:
ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL
Server]Invalid object name 'Node'. (208) (SQLExecDirectW)")
I am actively researching this.
Try this:
def read(conn):
print("Read")
cursor = conn.cursor()
cursor.execute("select * from table")
allrows = cursor.fetchall()
for row in allrows:
print(f'row = {row}')
print()

Categories