1

Today is my 3rd day learning Python and despite numerous web searches I can't seem to get past this issue.

The code takes in input on the command line and passes it to the connection script fine and it connects. The problem comes when I try to connect the cursor to the connection object on the line that reads: cor = con.cursor(). I get the error message: AttributeError: 'str' object has no attribute 'cursor'. Basically all I'm trying to do is take in parameters for my connection string to connect to the database and then be able to run my query. I request anyone helping me to bear in mind I'm a starter so detailed answers would be very helpful. Thanks in advance.

Code below:

import pyodbc
import getpass
import sys
server_name = input('Enter Server Name: ')
database_name = input('Enter Database Name: ')
uid = input('Enter User ID: ')
password = getpass.getpass("Enter your password: ")
querystring = "select top 1 * from SomeTable"
conStr = ('pyodbc.connect'+"('DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s')") % (server_name, database_name, uid, password)
con = conStr
cur = con.cursor()   #Generates error on this line
cur.execute(querystring)
rows = cur.fetchall()
for row in rows:
    print(row)

1 Answer 1

3

This is just a concatenation of two strings, so a string (the parenthesis don't matter):

('pyodbc.connect'+"('blah')")

And string % (value, value) takes the left side string as a printf-style format string and inserts the given values in it. The result again is a string, so your conStr is just a string. A string that probably looks like a Python function call, but a string nonetheless.

I think you want to just call pyodbc.connect():

con = pyodbc.connect(
      'DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s' % 
      (server_name, database_name, uid, password))

Though I'm not sure about the syntax of the strint it expects as argument. At least according to this that looks about fine.

Sign up to request clarification or add additional context in comments.

1 Comment

It was the parenthesis after the last % that was messing up everything. Thanks pikachu it works perfectly. Very grateful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.