1+ import mysql from 'mysql' ;
2+ import { currentDateTime } from "./server.js"
3+
4+ const pool = mysql . createPool ( {
5+ host : "127.0.0.1" ,
6+ user : "root" ,
7+ password : "" ,
8+ database : "testdb" ,
9+ connectionLimit : 10
10+ } ) ;
11+
12+ console . log ( "[" + currentDateTime ( ) + "] [OK] MYSQL POOL CREATED SUCCESSFULLY" ) ;
13+
14+ export class Database {
15+ constructor ( table , columns , parameters ) {
16+ this . table = table ;
17+ this . columns = "" ;
18+ this . Rcolumns = "" ;
19+ this . parameters = parameters ;
20+ this . _P = "" ;
21+
22+ for ( let i = 0 ; i < columns . length ; i ++ ) {
23+ this . columns += columns [ i ] ;
24+ if ( i < columns . length - 1 ) {
25+ this . columns += ", " ;
26+ }
27+ }
28+
29+ for ( let i = 0 ; i < columns . length ; i ++ ) {
30+ this . Rcolumns += columns [ i ] + " = ?" ;
31+ if ( i < columns . length - 1 ) {
32+ this . Rcolumns += " AND " ;
33+ }
34+ }
35+
36+ for ( let i = 0 ; i < parameters . length ; i ++ ) {
37+ this . _P += "?" ;
38+ if ( i < columns . length - 1 ) {
39+ this . _P += ", " ;
40+ }
41+ }
42+ }
43+
44+ insert ( ) {
45+ pool . query ( "INSERT INTO " + this . table + " (" + this . columns + ") VALUES (" + this . _P + ")" , this . parameters , function ( err , results ) {
46+ if ( err ) throw err ;
47+ } ) ;
48+ }
49+
50+ read ( ) {
51+ return new Promise ( ( resolve , reject ) => {
52+ pool . query ( "SELECT * FROM " + this . table + " WHERE " + this . Rcolumns , this . parameters , function ( err , results ) {
53+ if ( err ) throw err ;
54+ resolve ( results ) ;
55+ } ) ;
56+ } ) ;
57+ }
58+
59+ count ( ) {
60+ return new Promise ( ( resolve , reject ) => {
61+ pool . query ( "SELECT COUNT(*) AS count FROM " + this . table + " WHERE " + this . columns + " = " + this . _P , this . parameters , function ( err , results ) {
62+ if ( err ) throw err ;
63+ resolve ( results [ 0 ] . count ) ;
64+ } ) ;
65+ } ) ;
66+ }
67+ }
0 commit comments