Inserting values from Python into SQL Server

0

I want to insert values into a SQL Server table, from Python.

Here is my table in SQL Server:

CREATE TABLE DB.type.[Ref] 
(
    [Type_Ref] varchar(65),
    [ID_match] varchar(65),
    [Data] varchar(65)

    PRIMARY KEY ([Type_Ref], [ID_match])
)

To insert values from python I wrote this code:

conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
                              'Server=????;'
                              'Database=DB;'
                              'Trusted_Connection=yes;')


cursor = conn.cursor()

sql = "INSERT INTO DB.Ref (Type_Ref, ID_match, Data) VALUES (?, ?, ?)"
cursor.execute(sql, (DATA[Type_Ref], DATA[ID_match], DATA[Data]))

conn.commit()
cursor.close()
conn.close()

However, when I run Python, I don't see any rows of data in SQL Server...

I noticed my IDE is giving this, after I run the python code above:

Process finished with exit code -1073741819 (0xC0000005)

Solution: I solved this problem by deleting the table in sql-server and create a new one.

python
sql-server
asked on Stack Overflow Jun 25, 2020 by Sofia • edited Jul 1, 2020 by Sofia

3 Answers

0

I think you are not building your conn object correctly. When I try to match your pattern, I receive a TypeError. Try this instead:

server='server'
database='database'
user='username'
password='secret'

conn = pyodbc.connect(
    server=server,
    database=database,
    user=username,
    password=password,
    port=1433,
    driver='ODBC Driver 17 for SQL Server'
)

The rest of your code looks like it should work fine.

answered on Stack Overflow Jun 25, 2020 by Milo
0

try the following:

Columns = ['Type_Ref', 'ID_match', 'Data']
sql = "INSERT INTO dbo.Ref([Type_Ref], [ID_match], [Data]) VALUES (?,?,?)"
cursor.executemany(sql, DATA[Columns].values.tolist())
conn.commit()
answered on Stack Overflow Jun 25, 2020 by sacse
0

Thaks for the help, I solved this problem by deleting the table in sql-server and create a new one.

answered on Stack Overflow Jul 3, 2020 by Sofia

User contributions licensed under CC BY-SA 3.0