我在连接数据库MySQL方面遇到了麻烦。我用databese编写了一个控制台项目,我在这里有一个类ConnectionManager
。现在我开始写网站了。我想连接数据库ang只需将我的工作类Connection conn = ConnectionManager.getConnection();
复制到新的动态项目中。但是这个类返回NULL而不是连接。也许你知道哪里有问题。
先感谢您!
连接器已添加。 NullPointer异常由import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private static String jdbcUrl = "jdbc:mysql://localhost:3306/registration";
private static String user = "root";
private static String password = "root";
private static Connection connection = null;
public static Connection getConnection()
{
if (connection == null)
{
initializeConnection();
}
return connection;
}
private static void initializeConnection()
{
Connection conn;
try {
conn = DriverManager.getConnection(jdbcUrl,user,password);
connection = conn;// doesn't execute and I don't know why
} catch (SQLException e) {
e.printStackTrace();
}
}}
Connection conn = ConnectionManager.getConnection();
使用:var danu = ["nu", "da", "nu", "da", "da", "da", "da", "da", "da", "nu", "nu"],
abc2 = ["2", "3", "2", "3", "3", "2", "2"];
danu.reduce(function (r, a, i, o) {
o[i] = a === 'da' ? abc2[r++] : a;
return r;
}, 0);
document.write('<pre>' + JSON.stringify(danu, 0, 4) + '</pre>');
答案 0 :(得分:0)
尝试制作构造函数并在其中添加代码。我正在做同样的事情和它的工作。像这样: -
public Connection() {
// TODO Auto-generated constructor stub
try {
if (connection == null)
{
initializeConnection();
}
return connection;
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 1 :(得分:0)
可能不止一个原因
1-检查您的用户权限
GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;
GRANT ALL PRIVILEGES ON * . * TO 'root'@'localhost';
2-检查你的jdbc网址及其端口。确保3306端口可用于使用mysql
jdbc:mysql://localhost:3306/registration
3-检查你的jar文件
测试您的连接
String dbUrl= "jdbc:mysql://localhost:3306/javabase";
String username = "root";
String password = "root";
try (Connection connection = DriverManager.getConnection(dbUrl, username, password)) {
System.out.println("Connected to DB!");
} catch (SQLException e) {
throw new IllegalStateException("Error: ", e);
}
4-检查您的用户密码。 如果您不确定更改密码。
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('root');