创建连接不是一个函数

plupiseo  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(431)

我已经通过安装了node js mysql和mysql类型

"@types/mysql": "^2.15.4",
"mysql": "^2.15.0"

我用的是角为2的电子,所以在我的元件中,我想通过

import * as mysql from 'mysql'

 @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
 })

 export class AppComponent implements OnInit {
    connection: any;
    constructor() {
       this.connection = mysql.createConnection({
           host: 'localhost',
           user: 'root',
           password: '5378@Geowan5378',
           database: 'company'
        });

    this.connection.connect((err) => {
        if (err) {
            console.log('error connecting', err);
        }else{
            console.log("connection was a success ");
        }
    });

}   // DI

但现在我犯了个错误

TypeError: o.createConnection is not a function

这是唯一的组成部分,到目前为止,我只学习电子和mysql。我哪里出错了?
注意,当我调用

this.connection.connect

我不明白,这可能是由于网络库,这是不可用的浏览器,但在我的情况下,正在运行 electron . 启动我的应用程序,所以我不使用浏览器
或者,我怎样才能在不使用服务器端框架的情况下直接将应用程序与mysql连接起来呢

gv8xihay

gv8xihay1#

您必须使用remote-from-electron api来要求mysql,而不是使用import。
在index.html上声明远程全局变量

<html>
<head>
...
</head>
<body>

<script>
var remote = require('electron').remote;
</script>
</body>
</html>

在app.component.ts上使用远程

declare var remote :any; // declare remote as any variable

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
 })

 export class AppComponent implements OnInit {
    connection: any;
    constructor() {
      var mysql = remote.require('mysql'); //require mysql with electron remote
       this.connection = mysql.createConnection({
           host: 'localhost',
           user: 'root',
           password: '5378@Geowan5378',
           database: 'company'
        });

    this.connection.connect((err) => {
        if (err) {
            console.log('error connecting', err);
        }else{
            console.log("connection was a success ");
        }
    });

}   // DI

希望对您有所帮助,我建议您改进mysql的加载方式和服务,使其高效地进行查询等。
编辑:或使用我的模块https://github.com/mochrira/ngx-mysql 学习如何使用它

相关问题