简体   繁体   中英

Python AttributeError: 'str' object has no attribute 'cursor'

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM