Search code examples
pythonsqlsql-serverpython-3.xpypyodbc

Insert data in sql server with python


I want to insert data in the sql server from a raspberry pi with python. I tried with pypyodbc but it s not working properly. Can you guide me witch module to use.

import pyodbc 
conn = pyodbc.connect(
                     'DRIVER={SQL Server Native Client 11.0};'
                     'SERVER=server;'
                     'Integrated_Security=false;'
                     'Trusted_Connection=no;'
                     'UID=pi;'
                     'PWD=pi;'
                     'DATABASE= database'
                 )
cursor = conn.cursor()
cursor.execute('SELECT * FROM database.table')

for row in cursor:
    print(row)

yodbc.InterfaceError: ('28000', '[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user \'pi\'. (18456) (SQLDriverConnect); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database " database" requested by the login. The login failed. (4060); [28000] [Microsoft][SQL Server Native Client 11.0]Invalid connection string attribute (0); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user \'pi\'. (18456); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database " database" requested by the login. The login failed. (4060); [28000] [Microsoft][SQL Server Native Client 11.0]Invalid connection string attribute (0)')


Solution

  • So a colleague just passed by me and told me to put all the data between '' only in 1 row Also i removed 'Integrated_Security=false;'Trusted_Connection=no; as someone told me

    The working code

    something='something'
    import pyodbc 
    conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=srv;DATABASE=datavase;UID=pi;PWD=pass')
    cursor = conn.cursor()
    cursor.execute("insert into test values (?, 'awesome library ')",var)
    cursor.execute('SELECT * FROM test')
    for row in cursor:
        print(row)