All codes using Python
This guide provides step-by-step instructions on how to run a Python script that connects to a SQL Server database, reads data from a table, inserts new data, and prints the updated table.
The script uses pyodbc
, a Python library that facilitates connections to ODBC databases.
-
Python 3.6 or above installed. If you do not have Python installed, you can download it from the official site - https://www.python.org/downloads/
-
SQL Server Database: You should have a SQL Server database set up with the appropriate permissions to read and write data.
-
pyodbc module: The pyodbc module should be installed on your system. If it's not, you can install it using pip:
pip install pyodbc
-
Clone the repository to your local machine or download the python script.
-
Open the Python file in your preferred code editor.
-
Update the SQL Server connection string with your server details:
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=Enter Your Server Name;"
"Database=ali;"
"Trusted_Connection=yes;")
Replace Enter Your Server Name
with the name of your SQL Server. Make sure that the Database
value matches the name of your database.
- The script is set to select all records from the table named
make
:
cursor.execute("Select * from make")
If your table has a different name, replace make
with your table's name.
- The script inserts three new records into the
make
table:
sopi= "insert into make (name) values (?)"
data= [('Uop'),('pou'),('fff')]
for i in data:
cursor.execute(sopi,i)
If you wish to add different records, modify the data
variable accordingly.
- Save the changes and run the script.
The script will then connect to your database, select all records from the make
table, insert the new records, and print all the records from the updated make
table.
The script includes a commented out section that creates a new table called lake
. If you need to create this table, uncomment these lines:
# cursor.execute("CREATE TABLE lake ( id int identity(1,1), name VARCHAR(128) UNIQUE,PRIMARY KEY(id))")
# cnxn.commit()
Then, modify the table name, column names, and column types to suit your needs.