AngularJS 本身并没有直接操作 SQL 数据库的功能,因为 AngularJS 是一个前端 JavaScript 框架,通常用于构建用户界面。SQL 数据库通常由后端(如 PHP、Node.js、Java、ASP.NET 等)处理。而 AngularJS 通常通过与后端服务器的 HTTP 请求(如通过 ngResource
或 $http
服务)来与数据库进行交互。
基本概念
- 前端(AngularJS):通过 HTTP 请求(如 AJAX 请求)从服务器获取数据。
- 后端(例如 Node.js / PHP / Java 等):与数据库(如 MySQL、PostgreSQL、SQLite 等)交互,执行 SQL 查询,并将数据返回给前端。
示例:AngularJS 与 SQL 数据库的交互
这里是一个使用 AngularJS 与后端服务器(Node.js)交互的简单示例:
1. 前端(AngularJS)代码:
首先,在 AngularJS 中,你可以使用 $http
服务向服务器发送请求,获取数据。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS 与 SQL 数据库 示例</title>
</head>
<body ng-controller="myController">
<h1>用户列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function($scope, $http) {
// 获取用户数据
$http.get('http://localhost:3000/users') // 向后端请求数据
.then(function(response) {
$scope.users = response.data;
});
});
</script>
</body>
</html>
说明:
- 上述代码通过 AngularJS 的
$http
服务从后端服务器获取用户数据。我们假设服务器提供了一个GET /users
的 API,返回包含用户数据的 JSON 格式数据。 - 在响应成功后,将数据存储到
$scope.users
中,并通过ng-repeat
显示在表格中。
2. 后端(Node.js + MySQL)代码:
在服务器端,您可以使用 Node.js 和 MySQL 来处理 SQL 查询并返回数据。
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3000;
// 创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test_db'
});
// 连接数据库
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database: ' + err.stack);
return;
}
console.log('Connected to the database as id ' + connection.threadId);
});
// 提供一个 GET 路由,返回数据库中的用户数据
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (err, results) => {
if (err) {
res.status(500).send('Error retrieving data');
return;
}
res.json(results); // 返回查询到的用户数据
});
});
// 启动服务器
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
说明:
- 使用
mysql
模块连接到 MySQL 数据库,并执行 SQL 查询来获取用户数据。 - 当接收到
/users
路由的请求时,查询users
表并将结果以 JSON 格式返回。
3. SQL 数据库:
假设我们已经有一个名为 test_db
的数据库,并且有一个 users
表,其结构如下:
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
INSERT INTO users (name, email) VALUES
('John Doe', 'john.doe@example.com'),
('Jane Smith', 'jane.smith@example.com'),
('Mike Johnson', 'mike.johnson@example.com');
说明:
- 我们创建了一个名为
users
的表,并插入了几条测试数据。
总结:
- 前端(AngularJS):使用
$http
或ngResource
与后端进行 HTTP 请求(如 GET、POST 等),获取或发送数据。 - 后端(Node.js + MySQL):使用数据库驱动(如
mysql
模块)执行 SQL 查询,并返回结果给前端。 - AngularJS 和 SQL 之间的交互主要通过后端服务完成,而不是直接在 AngularJS 中执行 SQL。
通过这种方式,AngularJS 可以与后端的 SQL 数据库进行交互,创建具有动态数据的 Web 应用程序。
发表回复