当然,以下是两段简单的JavaScript代码示例,用于防止SQL注入:,,1. 使用参数化查询(适用于Node.js和MySQL):,“
javascript,const mysql = require('mysql');,const connection = mysql.createConnection({, host: 'localhost',, user: 'root',, password: 'password',, database: 'mydatabase',});,,connection.connect();,,const userId = 1; // 假设这是用户输入的ID,const query = 'SELECT * FROM users WHERE id = ?';,connection.query(query, [userId], (error, results) => {, if (error) throw error;, console.log(results);,});,,connection.end();,
`,,2. 使用ORM框架(如Sequelize):,
`javascript,const { Sequelize, Model, DataTypes } = require('sequelize');,const sequelize = new Sequelize('sqlite::memory:');,,class User extends Model {},User.init({, username: DataTypes.STRING,, birthday: DataTypes.DATE,}, { sequelize, modelName: 'user' });,,async function findUserById(id) {, try {, const user = await User.findOne({ where: { id: id } });, console.log(user);, } catch (error) {, console.error(error);, },},,sequelize.sync().then(() => {, findUserById(1); // 假设这是用户输入的ID,});,
“,,这两段代码分别展示了如何使用参数化查询和ORM框架来防止SQL注入。在Web开发中,防止SQL注入攻击是至关重要的,因为这种攻击可能导致数据泄露、数据篡改甚至系统崩溃,下面分享两段简单的JavaScript代码,帮助开发者在前端进行基本的输入验证,以减少SQL注入的风险。
示例代码一:使用正则表达式过滤特殊字符
function sanitizeInput(input) { const specialChars = /[