相关文章推荐
飘逸的煎鸡蛋  ·  PyTorch 0.4.0 正式版 - ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am using Python 3.6, pyodbc, and connect to SQL Server.

I am trying make connection to a database, then creating a query with parameters.

Here is the code:

import sys
import pyodbc
# connection parameters
nHost = 'host'
nBase = 'base'
nUser = 'user'
nPasw = 'pass'
# make connection start
def sqlconnect(nHost,nBase,nUser,nPasw):
        return pyodbc.connect('DRIVER={SQL Server};SERVER='+nHost+';DATABASE='+nBase+';UID='+nUser+';PWD='+nPasw)
        print("connection successfull")
    except:
        print ("connection failed check authorization parameters")  
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop
# if run WITHOUT parameters THEN everything is OK   
ask = input ('Go WITHOUT parameters y/n ?')
if ask == 'y':
    # SQL without parameters start
    res = cursor.execute('''
    SELECT * FROM TABLE 
    WHERE TABLE.TIMESTAMP BETWEEN '2017-03-01T00:00:00.000' AND '2017-03-01T01:00:00.000'
    # SQL without parameters stop
    # print result to console start
    row = res.fetchone()
    while row:
        print (row)
        row = res.fetchone()
    # print result to console stop
# if run WITH parameters THEN ERROR
ask = input ('Go WITH parameters y/n ?') 
if ask == 'y':
    # parameters start
    STARTDATE = "'2017-03-01T00:00:00.000'"
    ENDDATE = "'2017-03-01T01:00:00.000'"
    # parameters end
    # SQL with parameters start
    res = cursor.execute('''
    SELECT * FROM TABLE 
    WHERE TABLE.TIMESTAMP BETWEEN :STARTDATE AND :ENDDATE
    ''', {"STARTDATE": STARTDATE, "ENDDATE": ENDDATE})
    # SQL with parameters stop
    # print result to console start
    row = res.fetchone()
    while row:
        print (row)
        row = res.fetchone()
    # print result to console stop

When I run the program without parameters in SQL, it works.

When I try running it with parameters, an error occurred.

Parameters in an SQL statement via ODBC are positional, and marked by a ?. Thus:

# SQL with parameters start
res = cursor.execute('''
SELECT * FROM TABLE 
WHERE TABLE.TIMESTAMP BETWEEN ? AND ?
''', STARTDATE, ENDDATE)
# SQL with parameters stop

Plus, it's better to avoid passing dates as strings. Let pyodbc take care of that using Python's datetime:

from datetime import datetime
STARTDATE = datetime(year=2017, month=3, day=1)
ENDDATE = datetime(year=2017, month=3, day=1, hour=0, minute=0, second=1)

then just pass the parameters as above. If you prefer string parsing, see this answer.

Thank you! I think it is right way, but i have next error: pyodbc .DataError: <'22007', '[22007]' – Aleks Apr 19, 2017 at 9:57 It's an Invalid datetime format error (see learn.microsoft.com/en-us/sql/odbc/reference/appendixes/…). I thought this might happen. You should try using a datetime like this: from datetime import datetime ... STARTDATE = datetime(year=2017, month=1, ...) – themiurge Apr 19, 2017 at 10:02

If you're trying to use pd.to_sql() like me I fixed the problem by passing a parameter called chunksize.

df.to_sql("tableName", engine ,if_exists='append', chunksize=50)

hope this helps

i tryied and have a lot of different errors: 42000, 22007, 07002 and others

The work version is bellow:

import sys
import pyodbc
import datetime
# connection parameters
nHost = 'host'
nBase = 'DBname'
nUser = 'user'
nPasw = 'pass'
# make connection start
def sqlconnect(nHost,nBase,nUser,nPasw):
        return pyodbc.connect('DRIVER={SQL Server};SERVER='+nHost+';DATABASE='+nBase+';UID='+nUser+';PWD='+nPasw)
    except:
        print ("connection failed check authorization parameters")  
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop
STARTDATE = '11/2/2017'
ENDDATE = '12/2/2017'
params = (STARTDATE, ENDDATE)
# SQL with parameters start
sql = ('''
SELECT * FROM TABLE 
WHERE TABLE.TIMESTAMP BETWEEN CAST(? as datetime) AND CAST(? as datetime)
# SQL with parameters stop
# print result to console start
query = cursor.execute(sql, params)
row = query.fetchone()
while row:
    print (row)
    row = query.fetchone()
# print result to console stop  
say = input ('everething is ok, you can close console')

I fixed this issue with code if you are using values through csv.

for i, row in read_csv_data.iterrows():
cursor.execute('INSERT INTO ' + self.schema + '.' + self.table + '(first_name, last_name, email, ssn, mobile) VALUES (?,?,?,?,?)', tuple(row))
                This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
– Deenadhayalan Manoharan
                Sep 8, 2022 at 9:26
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.