Python Office Automation – Processing JSOM data and manipulating SQL Server databases

Python Office Automation – Processing JSOM data and manipulating SQL Server databases

The following is a catalog of articles from previous issues, please check them out if needed.
Python Office Automation – Operation of Excel and Word using
Python Office Automation – Python sending email and integration of Outlook
Python Office Automation – Processing of PDF documents and PPT documents
Python Office Automation – Operation of Excel documents and databases, setting up scheduled tasks
Python Office Automation – Manipulate and manage files/folders with CSV files
Python Office Automation – Analyze and chart data
Python Office Automation – Image processing and file encryption and decryption
Python Office Automation – Speech recognition and text-to-speech conversion
Python office automation – log analysis and automated FTP operations
Python office automation – network monitoring and compressed file processing
Python office automation – file comparison, merging and manipulation of xml files
Python office automation – scheduled email reminders and audio and video file processing



Preface

Python office automation is the process of using the Python programming language to create scripts and programs to simplify, speed up and automate daily office tasks and workflows. It is based on Python's powerful functions and rich third-party libraries, enabling it to handle various office tasks, such as document processing, data analysis, email management, network communication, etc.


1. Use Python to process JSON data

Processing JSON data in Python is a common task because JSON is a commonly used data format used to transfer and store data between applications.

1. Parse JSON data:

To parse JSON data, you can use the built-in json library.

import json

# JSON字符串
json_data = '{"name": "John", "age": 30, "city": "New York"}'

# 解析JSON数据
data = json.loads(json_data)

# 访问数据
print(data["name"]) # 输出:John
print(data["age"]) # 输出:30

2. Convert Python data to JSON

You can use the json.dumps() method to convert Python data into JSON format.

import json

# Python字典
data = {
    
    
	"name": "John",
	"age": 30,
	"city": "New York"
	}
	
# 将数据转换为JSON字符串
json_data = json.dumps(data)

# 输出JSON字符串
print(json_data) # 输出:{"name": "John", "age": 30, "city": "New York"}

3. Read data from JSON file

import json

# 从JSON⽂件读取数据
with open("data.json", "r") as json_file:
	data = json.load(json_file)

# 访问数据
print(data["name"])

4. Write data to JSON file

import json

# Python字典
data = {
    
    
	"name": "John",
	"age": 30,
	"city": "New York"
	}

# 将数据写⼊JSON⽂件
with open("data.json", "w") as json_file:
	json.dump(data, json_file)

5. Handling nested JSON

JSON can contain nested structures, and nested JSON data can be processed through level-by-level access.

import json

# 嵌套的JSON数据
json_data = '{"person": {"name": "John", "age": 30}}'

# 解析JSON数据
data = json.loads(json_data)

# 访问嵌套数据
print(data["person"]["name"]) # 输出:John

These examples show basic operations on how to process JSON data in Python. Whether parsing JSON data, converting Python data to JSON, or reading or writing data from a JSON file, Python's json library provides convenient tools to perform these tasks. JSON data processing is important for many applications such as interacting with APIs, reading and writing configuration files, and data exchange.

2. How to operate SQL Server database with Python

To operate a SQL Server database in Python, you can use different libraries and methods, but one of the most common and widely used methods is to use the pyodbc library.

1. Install pyodbc library

First, make sure the pyodbc library is installed. You can install it using the following command:

pip install pyodbc

2. Establish a database connection

To use pyodbc to connect to a SQL Server database, you need to provide a connection string, including database server address, database name, user name, password and other information. The following is an example of connecting to a SQL Server database:

import pyodbc

# 创建数据库连接字符串  
server = 'your_server_name'  
database = 'your_database_name'  
username = 'your_username'  
password = 'your_password'  
driver= '{ODBC Driver 17 for SQL Server}' # 使用的ODBC驱动程序名称可能会因版本而异  
connection_string = f'DRIVER={
      
      driver};SERVER={
      
      server};DATABASE={
      
      database};UID={
      
      username};PWD={
      
      password}'  
  
# 建立数据库连接  
conn = pyodbc.connect(connection_string)  

Please replace server_name, database_name, username and password with your own database connection information.

3. Execute SQL query

To use a database connection to execute SQL queries, you can use the cursor() method to create a cursor object, and then use the cursor to execute SQL statements.

# 创建游标
cursor = connection.cursor()

# 执⾏SQL查询
cursor.execute("SELECT * FROM table_name")

# 获取查询结果
results = cursor.fetchall()

# 打印结果
for row in results:
	print(row)

Please replace table_name with the name of the table to be queried, and perform other SQL operations as needed, such as inserting, updating, or deleting data.

4. Close the connection

After completing the database operation, don't forget to close the connection to release resources.

# 关闭游标
cursor.close()
# 关闭数据库连接
connection.close()

This is a basic join and query example. According to the needs, more complex operations can be performed, such as parameterized queries, transaction management, etc. In addition, you can use ORM (Object Relational Mapping) libraries such as SQLAlchemy to more easily interact with SQL Server databases and associate database operations with Python objects.


Summarize

The above is the content shared today. I hope it will be helpful to friends who have seen it. I will continue to update the article sharing of python office automation in the future, so you can continue to pay attention.

Supongo que te gusta

Origin blog.csdn.net/u014740628/article/details/135377475
Recomendado
Clasificación