MySQL 数据库 XML 数据处理在图书目录管理中的实战

MySQL 数据库阿木 发布于 9 天前 2 次阅读


XML 数据处理在图书目录管理中的实战:代码编辑模型

随着互联网和信息技术的发展,XML(可扩展标记语言)已成为数据交换和存储的重要格式。在图书目录管理系统中,XML 数据格式因其灵活性和可扩展性,被广泛应用于数据的存储和交换。本文将围绕XML 数据处理在图书目录管理中的应用,通过代码编辑模型,展示如何实现图书信息的增删改查等功能。

1. 系统设计

1.1 系统架构

本系统采用前后端分离的架构,前端使用HTML、CSS和JavaScript等技术实现用户界面,后端使用Python语言和Flask框架进行数据处理。数据库采用MySQL,用于存储图书信息。

1.2 数据库设计

在MySQL数据库中,创建一个名为`books`的表,用于存储图书信息。表结构如下:

sql

CREATE TABLE books (


id INT AUTO_INCREMENT PRIMARY KEY,


title VARCHAR(255) NOT NULL,


author VARCHAR(255) NOT NULL,


isbn VARCHAR(20) NOT NULL,


publish_date DATE NOT NULL,


category VARCHAR(50) NOT NULL


);


1.3 XML 数据结构

图书信息以XML格式存储,结构如下:

xml

<library>


<book>


<id>1</id>


<title>Python编程:从入门到实践</title>


<author>埃里克·马瑟斯</author>


<isbn>9787115428746</isbn>


<publish_date>2019-01-01</publish_date>


<category>编程</category>


</book>


<!-- 更多图书信息 -->


</library>


2. 后端实现

2.1 Flask框架搭建

安装Flask框架:

bash

pip install flask


然后,创建一个名为`app.py`的文件,编写以下代码:

python

from flask import Flask, request, jsonify


import xml.etree.ElementTree as ET


import pymysql

app = Flask(__name__)

数据库连接配置


db_config = {


'host': 'localhost',


'user': 'root',


'password': 'password',


'db': 'library'


}

连接数据库


def get_db_connection():


connection = pymysql.connect(db_config)


return connection

获取所有图书信息


@app.route('/books', methods=['GET'])


def get_books():


connection = get_db_connection()


try:


with connection.cursor() as cursor:


sql = "SELECT FROM books"


cursor.execute(sql)


result = cursor.fetchall()


books = []


for row in result:


book = {


'id': row[0],


'title': row[1],


'author': row[2],


'isbn': row[3],


'publish_date': row[4],


'category': row[5]


}


books.append(book)


return jsonify(books)


finally:


connection.close()

添加图书信息


@app.route('/books', methods=['POST'])


def add_book():


connection = get_db_connection()


try:


with connection.cursor() as cursor:


xml_data = request.data


root = ET.fromstring(xml_data)


book = {


'title': root.find('title').text,


'author': root.find('author').text,


'isbn': root.find('isbn').text,


'publish_date': root.find('publish_date').text,


'category': root.find('category').text


}


sql = "INSERT INTO books (title, author, isbn, publish_date, category) VALUES (%s, %s, %s, %s, %s)"


cursor.execute(sql, (book['title'], book['author'], book['isbn'], book['publish_date'], book['category']))


connection.commit()


return jsonify({'message': 'Book added successfully'})


finally:


connection.close()

更新图书信息


@app.route('/books/<int:book_id>', methods=['PUT'])


def update_book(book_id):


connection = get_db_connection()


try:


with connection.cursor() as cursor:


xml_data = request.data


root = ET.fromstring(xml_data)


book = {


'title': root.find('title').text,


'author': root.find('author').text,


'isbn': root.find('isbn').text,


'publish_date': root.find('publish_date').text,


'category': root.find('category').text


}


sql = "UPDATE books SET title=%s, author=%s, isbn=%s, publish_date=%s, category=%s WHERE id=%s"


cursor.execute(sql, (book['title'], book['author'], book['isbn'], book['publish_date'], book['category'], book_id))


connection.commit()


return jsonify({'message': 'Book updated successfully'})


finally:


connection.close()

删除图书信息


@app.route('/books/<int:book_id>', methods=['DELETE'])


def delete_book(book_id):


connection = get_db_connection()


try:


with connection.cursor() as cursor:


sql = "DELETE FROM books WHERE id=%s"


cursor.execute(sql, (book_id,))


connection.commit()


return jsonify({'message': 'Book deleted successfully'})


finally:


connection.close()

if __name__ == '__main__':


app.run(debug=True)


2.2 XML 数据处理

在Flask应用中,使用`xml.etree.ElementTree`模块解析XML数据。以下代码展示了如何解析XML数据并获取图书信息:

python

import xml.etree.ElementTree as ET

def parse_xml(xml_data):


root = ET.fromstring(xml_data)


book = {


'id': root.find('id').text,


'title': root.find('title').text,


'author': root.find('author').text,


'isbn': root.find('isbn').text,


'publish_date': root.find('publish_date').text,


'category': root.find('category').text


}


return book


3. 前端实现

3.1 HTML界面

创建一个名为`index.html`的文件,编写以下代码:

html

<!DOCTYPE html>


<html lang="en">


<head>


<meta charset="UTF-8">


<title>图书目录管理系统</title>


</head>


<body>


<h1>图书目录管理系统</h1>


<div>


<h2>添加图书</h2>


<form id="add-book-form">


<input type="text" id="title" placeholder="书名" required>


<input type="text" id="author" placeholder="作者" required>


<input type="text" id="isbn" placeholder="ISBN" required>


<input type="date" id="publish_date" placeholder="出版日期" required>


<input type="text" id="category" placeholder="分类" required>


<button type="submit">添加图书</button>


</form>


</div>


<div>


<h2>图书列表</h2>


<table id="books-table">


<thead>


<tr>


<th>编号</th>


<th>书名</th>


<th>作者</th>


<th>ISBN</th>


<th>出版日期</th>


<th>分类</th>


<th>操作</th>


</tr>


</thead>


<tbody>


<!-- 图书信息 -->


</tbody>


</table>


</div>


<script src="app.js"></script>


</body>


</html>


3.2 JavaScript交互

创建一个名为`app.js`的文件,编写以下代码:

javascript

document.getElementById('add-book-form').addEventListener('submit', function(event) {


event.preventDefault();


const title = document.getElementById('title').value;


const author = document.getElementById('author').value;


const isbn = document.getElementById('isbn').value;


const publish_date = document.getElementById('publish_date').value;


const category = document.getElementById('category').value;

const xml_data = `<book>


<title>${title}</title>


<author>${author}</author>


<isbn>${isbn}</isbn>


<publish_date>${publish_date}</publish_date>


<category>${category}</category>


</book>`;

fetch('/books', {


method: 'POST',


headers: {


'Content-Type': 'application/xml'


},


body: xml_data


})


.then(response => response.json())


.then(data => {


console.log(data);


// 更新界面


})


.catch(error => {


console.error('Error:', error);


});


});

// 获取图书列表


fetch('/books')


.then(response => response.json())


.then(data => {


const table_body = document.getElementById('books-table').getElementsByTagName('tbody')[0];


data.forEach(book => {


const row = table_body.insertRow();


row.insertCell().innerText = book.id;


row.insertCell().innerText = book.title;


row.insertCell().innerText = book.author;


row.insertCell().innerText = book.isbn;


row.insertCell().innerText = book.publish_date;


row.insertCell().innerText = book.category;


const delete_cell = row.insertCell();


const delete_button = document.createElement('button');


delete_button.innerText = '删除';


delete_button.onclick = function() {


fetch(`/books/${book.id}`, {


method: 'DELETE'


})


.then(response => response.json())


.then(data => {


console.log(data);


// 更新界面


})


.catch(error => {


console.error('Error:', error);


});


};


delete_cell.appendChild(delete_button);


});


})


.catch(error => {


console.error('Error:', error);


});


});


4. 总结

本文通过代码编辑模型,展示了XML 数据处理在图书目录管理系统中的应用。通过Flask框架和MySQL数据库,实现了图书信息的增删改查功能。在实际应用中,可以根据需求扩展系统功能,如添加用户认证、权限控制等。