My project currently consists of a locally hosted set of JSP pages that connect to a mySQL database, that is also local.
I am trying to verify users that enter the site using the database. Yet the problem lies within the connection.
In the verification JSP page, I have this piece of code:
<%
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;
}
}
%>
I've tried various methods of connecting, yet none of them seem to work.
The first one (Datasource
, not in comment) hits me with a java.lang.NullPointerException
. Page output: http://prntscr.com/ff37x9
The second one (single String
DriverManager
connection) connects, but doesn't recognise the database. However, when I add my_db
it tells me it doesn't find any database named "my_db
".
Third and fourth are same as the second.
I can't understand what's malfunctioning. Should I be aware of something else?
Edit: The connection is needed only for this page, as the rest of the site is managed through the session
object of Java
Thank you for your time.