If you want to connect your python code to SQL Server there is no direct method. You need to install packages for connecting SQL Server. To install package perform the following steps:

Open Python Environment in Visual Studio by clicking VIEW, Other Windows, then Python Environment.

Now click on Python Interpreter which you have installed in your system (Note: A Computer can contain more than 1 Python interpreter), select pip from the drop down and search form pypyodbc.

Note:"pypyodbc" is a module which is used to connect to the database and perform operations on that. pypyodbc can be used with any type of database: Oracle, SQL Server, MySQL, Microsoft Access or Excel, etc.

After successfully installing pypyodbc. Now open SQL Server and create a database and create table.

I am creating a database Payroll and inside that database I am creating a table named EmployeeMaster which contains the following fields.

cursor() : This is a method which returns a new cursor object using the connection.

execute() : Prepares and executes SQL.

commit() :Commits any pending transaction to the database.

Output

And check the database, it will contain data which you have inserted.

Using Question Mark (?)

We can also execute our query with question mark sign. Sometimes we need to insert our data at run time and we want to form our query with the + symbol and sometimes we forget to open/close double quotes or single quotes or plus symbol. So we can also execute our query with Question Mark Sign ? like the following: