【发布时间】:2017-06-02 13:39:46
【问题描述】:
我的项目目前由一组本地托管的 JSP 页面组成,这些页面连接到 mySQL 数据库,这也是本地的。
我正在尝试验证使用数据库进入网站的用户。然而问题在于连接。
在验证JSP页面中,我有这段代码:
<%
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String server = "jdbc:mysql://localhost:3306/";
String database = "my_db";
String user = "user";
String pass = "password";
try {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser(user);
dataSource.setPassword(pass);
dataSource.setServerName(server);
dataSource.setDatabaseName(database);
connection = dataSource.getConnection();
//Class.forName("com.mysql.jdbc.Driver").newInstance();
//connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/?user=user&password=password");
//Class.forName("com.mysql.jdbc.Driver").newInstance();
//connection = DriverManager.getConnection(server/*+database*/+"?user="+user+"&password="+pass);
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//connection=DriverManager.getConnection(server/*+database*/,user,pass);
if(!connection.isClosed()){
//do stuff
}
}catch(Exception ex){
out.println("Cannot connect to database.<br>"+ex);
}finally{//Release Resources
if(resultSet!=null){
try{resultSet.close();}catch(SQLException sqlEx){}
resultSet = null;
}
if(statement != null){
try{statement.close();}catch(SQLException sqlEx){}
statement = null;
}
if(!connection.isClosed()){
try{connection.close();}catch(SQLException sqlEx){}
connection = null;
}
}
%>
我尝试了各种连接方法,但似乎都不起作用。
第一个(Datasource,未发表评论)用java.lang.NullPointerException 击中了我。页面输出:http://prntscr.com/ff37x9
第二个(单个StringDriverManager 连接)连接,但无法识别数据库。但是,当我添加 my_db 时,它告诉我它没有找到任何名为“my_db”的数据库。
第三和第四与第二相同。
我不明白发生了什么故障。我应该注意其他事情吗?
编辑:仅此页面需要连接,因为站点的其余部分通过 Java 的 session 对象进行管理
感谢您的宝贵时间。
【问题讨论】:
-
使用驱动程序管理器,您可以连接,对吗?您正在尝试连接 Wicht 数据库用户吗?
-
我正在尝试连接到本地数据库。这是我从 MySQL Workbench 获得的 JDBC 连接字符串:
jdbc:mysql://localhost:3306/?user=root -
但它不起作用;如果我尝试创建一个语句并执行它,它说它没有找到数据库。
-
你为什么用'?'在 url 字符串处?
-
@ThemistoklisGkasios 你提到你有 NPE,你能把堆栈跟踪放在这里吗? NPE 被扔在哪个类?