This is demo project how about python connect SQL Server.
With IDE, you can use VScode or Pycharm. Don't forget install Python.exe. In this example, I need to install pyodbc Let’s talk about each of the steps.
I' ll create a new database is test_python. The next, I add a new table is My_Table.
You can use to connect Python to SQL Server:
conn = pyodbc.connect('Driver={SQL Server};'
'Server=QUANGKUN\LINHQUANG;' 'Database=test_python;' 'Trusted_Connection=yes;')
Let’s review an example, where:
- The Server Name is: QUANGKUN/LINHQUANG
- The Database Name is: test_python
- The Table Name (with a dbo schema) is: dbo.My_Table
print("Read")
cursor = conn.cursor()
cursor.execute('SELECT * FROM test_python.dbo.My_Table')
for row in cursor:
___print(row)
I print the result in console.
print("Create")
cursor = conn.cursor()
cursor.execute( 'insert into test_python.dbo.My_Table(Name) values(?);', ('Dog'))
conn.commit()
read(conn)
print("Update")
cursor = conn.cursor()
cursor.execute( 'update test_python.dbo.My_Table set Name = ? where ID = ?;', ('Raichu', 1))
conn.commit()
read(conn)
print("Delete")
cursor = conn.cursor()
cursor.execute( 'delete from test_python.dbo.My_Table where Id = ?', 5 )
conn.commit()
read(conn)
print("Check")
cursor = conn.cursor()
cursor.execute('SELECT Name FROM test_python.dbo.My_Table Where Name = ?', "Raichu")
for row in cursor:
___print(row)
I print the result in console.
https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/