Java DB Connection Manager Best Practice - java

I have a connection manager code as follows:
public class ConnectionManager {
private final String driverName = "com.mysql.jdbc.Driver";
private final String connectionUrl = "jdbc:mysql://localhost:3306/student";
private final String userName = "root";
private final String userPass = "root";
private Connection con = null;
public ConnectionManager() {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
}
public Connection createConnection() {
try {
con = DriverManager.getConnection(connectionUrl, userName, userPass);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public void closeConnection() {
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
How can I improve this? I am thinking the following improvement:
) create a connection.properties. What is the best way to implement this? Should I put it the call of the property file on a singleton?
) Make the connection singleton.
Thank you.

If it's for a real application you'd better use a connection pool like this http://commons.apache.org/proper/commons-dbcp/.

Related

Fail to retrieve data from postgresql

this is my connection string for connection postgresql database .And using this code I am able to connect the db
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5433/Test", "youtube",
"1");
Then I am using the same code to retrieve some data .And I get this exception
org.postgresql.util.PSQLException: ERROR: "userdetail" NOT EXIST
Position: 27
which referr this line
con=GetDbConn();
So mytable name is UserDetail not userdetail I dont understand why am i getting this exception message
And this is my code
public class DbUtils {
private static final String DB_DRIVER="org.postgresql.Driver";
private static final String DB_CONN="jdbc:postgresql://127.0.0.1:5433/Test";
private static final String DB_USER="youtube";
private static final String DB_PASS="1";
public void SelectUserDetails() {
Connection con=null;
Statement statement;
String query="select isim,soyisim from UserDetail";
try {
con=GetDbConn();
statement= con.createStatement();
ResultSet resultSet=statement.executeQuery(query);
while(resultSet.next()){
String isimM=resultSet.getString("isim");
String soyisimM=resultSet.getString("soyisim");
System.out.println("isim :"+soyisimM+" soyisim: "+soyisimM);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static Connection GetDbConn() {
Connection con = null;
try {
Class.forName(DB_DRIVER);
con=DriverManager.getConnection(DB_CONN, DB_USER, DB_PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}

Null pointer exception after initialize

private static String dbURL = "jdbc:mysql://localhost:3306/mydb";
private static String username = "secret";
private static String password = "secret";
private static Connection conn = null;
public static void initDbConnection(){
try {
conn = DriverManager.getConnection(dbURL, username, password);
Class.forName("com.mysql.jdbc.Driver");
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void test3(){
initDbConnection();
try{
String sql = "SELECT * FROM Products";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()){
String name = result.getString("name");
System.out.println(name);
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
Why I'm getting null pointer exception on conn even though I called the initDbConnection() on test3() ? How will I elimate this problem?
Class.forName("com.mysql.jdbc.Driver");
should be the first line. As this load the mysql driver in the memory. Then you will acquire the connection.
So it should be
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, username, password);
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}

can't get connection to database through java class

i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

Cannot understand warning message: expected:<interface java.sql.Connection> but was:<class com.mysql.jdbc.JDBC4Connection>

I am getting this message in unit test expected:<interface java.sql.Connection> but was:<class com.mysql.jdbc.JDBC4Connection>
from my code:
#Test
public void connectionTest() throws SQLException{
Connection conn = ConnectionManager.createConnection();
assertEquals(Connection.class, conn.getClass());
conn.close();
}
My mock class for getting connection:
public class ConnectionManager {
#SuppressWarnings("unused")
public static Connection createConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/library";
String name = "root";
String password = "root";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, name, password);
} catch (ClassNotFoundException e) {
if (connection != null){
connection.close();
}
throw new SQLException(e);
}
return connection;
}
}
What is wrong with my code?
Your assert is fundamentally wrong.
Connection.class is an interface.
conn.getClass() will return a concrete class that implements that interface.

Returning the Connection from JDBC into a main method of Java?

Is it possible to return the type Connection?
And use it as a method passed by reference through out the program?
I find it makes the database interaction a lot easier if it is passed as a method.
public static Connection database(String database, String username, String password) {
String url = "jdbc:postgresql:" + database;
//LOAD DRIVER
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
//CONNECT TO DATABASE
try {
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
db = database("java_jdbc", "admin", "fake_password_1234");
}
You can do that.
Just remember to invoke close() on the connection to release its resources when done.
package mySystem;
import java.sql.*;
import javax.swing.*;
public class MySqlConnector {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver"); //register jdbc driver
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/inventory_db", "root", "");
// JOptionPane.showMessageDialog(null, "Connected to db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}

Categories