[Python 3.4] SQL Server connection Error: string indices must be integers

Hello I am new to python and I am attempting to connect to a localhost sql server database.

# Parameters
server = "MyServer"
DB = "NFL"

# Create the connection
conn = pyodbc.connect('DRIVER={SQL     Server};SERVER=' + DB['servername'] + ';DATABASE=' + DB['database'] + ';Trusted_Connection=yes')

# query db
sql = """

SELECT TD FROM Stats

"""

df = pd.sql.read_sql(sql, conn)
df.head()

But I get this error when I run my code

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + DB['servername'] + ';DATABASE=' + DB['database'] + ';Trusted_Connection=yes')
TypeError: string indices must be integers

Why would I be getting this error if a table can have strings or integers, and how can I fix this?

Posted Oct 26, 2016, 4:54 PM UTC

23
K900_K900•

That has nothing to do with tables at all. You're trying to access DB['servername'], where DB is the string "NFL". That doesn't make sense.

2
StartAndSelectOP•

Ah I see my mistake. Thanks!

1
novel_yet_trivial•
DB = "NFL"

You define "DB" as a sting. Then later

DB['servername'] 

You are trying to access it like a dictionary. The error is telling you that a string cannot be accessed that way. Did you overwrite your dictionary name?

2