例如:
某数据库某表的字段如下:
CREATE TABLE IF NOT EXISTS BooksInfo( BooksInfoId VARCHAR(20),/*primaryKey,需为图书id*/ title VARCHAR(50) NOT NULL,/*图书姓名*/ num INT UNSIGNED NOT NULL,/*图书总数目*/ pos VARCHAR(50) NOT NULL,/*图书位置*/ PRIMARY KEY (BooksInfoId) )
那么,进行防重插入的SQL语句如下:
INSERT INTO BooksInfo(BooksInfoId,title,num,pos) SELECT 'a115','数据结构与算法',500,'c区' FROM DUAL WHERE NOT EXISTS ( SELECT BooksInfoId,title,num,pos FROM BooksInfo WHERE BooksInfoId='a115' AND title='数据结构与算法' AND num=500 AND pos='c区' );
在base.js中:
var mysql = require('mysql') class Base { constructor() { this.CONNECT; } CreateConnect() { this.CONNECT = mysql.createConnection({ host: 'localhost', port: '3306', user: 'root', password: '0610', database: 'libraryManagementSystem' }) } } module.exports = { Base }
在bookData.js中:
const Base = require('./Base') const addData = "INSERT INTO BooksInfo(BooksInfoId,title,num,pos) SELECT ?,?,?,? FROM DUAL WHERE NOT EXISTS(SELECT BooksInfoId,title,num,pos FROM BooksInfo WHERE BooksInfoId=? AND title=? AND num=? AND pos=?);" class Books extends Base.Base { constructor() { super() } //增添数据 addData(message, callback) { this.CreateConnect() let CONNECT = this.CONNECT CONNECT.connect() CONNECT.query(addData, [message.BooksInfoId, message.title, message.num, message.pos, message.BooksInfoId, message.title, message.num, message.pos], (err, result) => { if (err) { console.log('[ADD ERROR]:', err.message); callback(-1); CONNECT.end(); return; } callback(0); CONNECT.end(); }) } } module.exports = { Books }
TIPS:在const addData中,字符串类型的变量‘?'无需用引号进行包括,否则会报错。