Using Python to Operate Microsoft SQL Server
To use Python to operate Microsoft SQL Server database connections and data insertion, querying, modification, and deletion, we can use the 'pyodbc' library. The following is a complete Python code example that demonstrates how to use 'pyodbc' to connect to a database, perform data insertion, query, modification, and deletion operations.
Firstly, ensure that the 'pyodbc' library is installed in the Python environment. If not installed, you can use the following command to install:
python
pip install pyodbc
Then, use the following code example to connect to a Microsoft SQL Server database and perform data insertion, query, modification, and deletion operations:
python
import pyodbc
#Database Connection Configuration
server = 'your_server_name'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'
#Connect to database
conn_string = f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password};'
conn = pyodbc.connect(conn_string)
#Insert Data
def insert_data():
cursor = conn.cursor()
sql = "INSERT INTO my_table (column1, column2) VALUES (?, ?)"
values = ('value1', 'value2')
cursor.execute(sql, values)
conn.commit()
Print ("Data insertion successful")
#Query data
def select_data():
cursor = conn.cursor()
sql = "SELECT * FROM my_table"
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
print(row)
#Update data
def update_data():
cursor = conn.cursor()
sql = "UPDATE my_table SET column1 = ? WHERE column2 = ?"
values = ('new_value', 'value2')
cursor.execute(sql, values)
conn.commit()
Print ("Data updated successfully")
#Delete data
def delete_data():
cursor = conn.cursor()
sql = "DELETE FROM my_table WHERE column1 = ?"
value = 'value1'
cursor.execute(sql, value)
conn.commit()
Print ("Data deleted successfully")
#Insert Data
insert_data()
#Query data
select_data()
#Update data
update_data()
#Delete data
delete_data()
#Close database connection
conn.close()
In the above example code, you need to add 'your'_ Server_ Name, your_ Database_ Name, your_ Username 'and' your '_ Replace 'password' with the actual database connection configuration. Additionally, 'my'_ Table 'needs to be replaced with the real data table name.
In actual use, please modify the code according to your own needs to ensure that the table name, column name, and query criteria match the actual situation.
This is a simple example that only demonstrates basic database operations, and you can further expand and optimize according to your own needs.