MySQL 数据横向展示通常指的是将数据库中的数据以表格的形式展示出来,使得每一列代表一个字段,每一行代表一条记录。这种展示方式便于用户直观地查看和理解数据。
原因:当数据量过大时,一次性加载所有数据会导致前端渲染缓慢,甚至出现卡顿现象。
解决方法:
原因:不同字段的数据长度可能不一致,导致表格展示时对齐不美观。
解决方法:
text-align等属性调整数据对齐方式。import mysql.connector
# 连接数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = db.cursor()
# 查询数据
cursor.execute("SELECT * FROM yourtable LIMIT 10")
# 获取数据
rows = cursor.fetchall()
# 打印数据
for row in rows:
print(row)
# 关闭连接
cursor.close()
db.close()<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MySQL 数据横向展示</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>字段1</th>
<th>字段2</th>
<th>字段3</th>
</tr>
</thead>
<tbody id="data-body">
</tbody>
</table>
<script>
// 假设这是从后端获取的数据
const data = [
['数据1', '数据2', '数据3'],
['数据4', '数据5', '数据6']
];
const dataBody = document.getElementById('data-body');
data.forEach(row => {
const tr = document.createElement('tr');
row.forEach(cell => {
const td = document.createElement('td');
td.textContent = cell;
tr.appendChild(td);
});
dataBody.appendChild(tr);
});
</script>
</body>
</html>