无法将我的nodejs连接到mysql

时间:2016-01-27 07:35:29

标签: mysql node.js jdbc

我的代码如下

    var JDBC = require('jdbc');
var jinst = require('jdbc/lib/jinst');
var Pool = require('jdbc/lib/pool');


// isJvmCreated will be true after the first java call.  When this happens, the
// options and classpath cannot be adjusted.
if (!jinst.isJvmCreated()) {
    // Add all java options required by your project here.  You get one chance to
    // setup the options before the first java call.
    jinst.addOption("-Xrs");
    // Add all jar files required by your project here.  You get one chance to
    // setup the classpath before the first java call.
    jinst.setupClasspath(['./jars/mysql-connector-java-5.1.38-bin.jar']);
}
var mySql = new JDBC({
    url: 'jdbc:mysql://localhost:3306/nodejs',
    drivername: 'com.mysql.jdbc.Driver',
    minpoolsize: 5,
    maxpoolsize: 10,
    user: 'root',
    password: 'root'
});
mySql.initialize(function(err) {
    if (err) {
        console.log(err);
    }
});

我在文件夹中有jar,而mysql在我的本地运行。但我收到以下错误

    java.lang.NoClassDefFoundError: com/mysql/jdbc/Driver
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
] cause: nodeJava_java_lang_NoClassDefFoundError {} }
{ [Error: Error running static method
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/nodejs
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
] cause: nodeJava_java_sql_SQLException {} }

请帮忙。在nodejs中是否有任何初始化命令?

1 个答案:

答案 0 :(得分:1)

我完全尝试了你的代码并且它有效,我认为你的路径setupClasspath()并不好。尝试使用绝对路径,只有在工作目录设置为您期望的情况下,相对路径才有效:

if (!jinst.isJvmCreated()) {
    jinst.addOption("-Xrs");
    jinst.setupClasspath([__dirname + '/jars/mysql-connector-java-5.1.38-bin.jar']);
}