问题
I need a with RxJS for MySQL in NodeJS. Could someone give me an example for one select?
On front-end I will use Angular2.
回答1:
In my case, I'm using the MySQL npm package in a desktop application made with Electron and Angular.
However the same should work even on a plain NodeJS application by installing and importing rxjs.
I've first installed mysql
and @types/mysql
package with:
npm install --saved-dev mysql @types/mysql
Then I've created a MySQL service:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Connection, ConnectionConfig, FieldInfo, MysqlError } from 'mysql';
const mysql = require('mysql');
@Injectable({
providedIn: 'root'
})
export class MysqlService {
private connection: Connection;
constructor() { }
createConnection(config: ConnectionConfig) {
this.connection = mysql.createConnection(config);
}
query(queryString: string, values?: string[]): Observable<{results?: Object[], fields?: FieldInfo[]}> {
return new Observable(observer => {
this.connection.query(queryString, values, (err: MysqlError, results?: Object[], fields?: FieldInfo[]) => {
if (err) {
observer.error(err);
} else {
observer.next({ results, fields });
}
observer.complete();
});
});
}
}
Now I can use my MysqlService
in any other service or component to connect to the mysql database and execute queries.
For example:
import { Component, OnInit } from '@angular/core';
import { MysqlService } from '../../services/mysql.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(
private mysqlService: MysqlService,
) { }
ngOnInit() {
this.mysqlService.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'my_password',
database: 'my_database',
});
this.mysqlService.query(`SELECT * FROM my_table WHERE name = 'Francesco'`).subscribe((data) => {
console.log(data);
})
}
}
来源:https://stackoverflow.com/questions/36639493/how-to-use-rxjs-mysql-and-nodejs