I was wondering if anyone could help me with a small problem. I'm trying to create a restfull service in Java using Jersey.
But I cannot find any examples on how to make a manual db connections. And If I do, the connection returns a nullpointer when querying the database.
public DbConnection()
{
try
{
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connection = DriverManager.getConnection("jdbc:mysql://url/team_staging?"
+ "user=X&password=X");
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SQLException ex)
{
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
Could someone point my in the right direction here? I don't want to use any ORM.
I find it hard to find good examples without hibernate or auto-generated rest service in netbeans...
My regards, Axl
I think your instinct to steer clear of an ORM solution is a good one.
You're writing a web service, which means it's deployed on a servlet/JSP engine at a minimum (eg Tomcat) or a full Java EE app server. I'd learn how to create a JNDI connection pool for your app server.
You want to externalize your connection parameters (eg driver, URL, etc.)
I don't see a class member for that connection. What happens when you exit the ctor? Is it out of scope? That would explain the NPE.
I'd write it this way:
package persistence;
public class DatabaseUtils {
private DatabaseUtils() {}
public static Connection getConnection(String driver, String url, String username, String password) throws Exception {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.