Prototype of Java Database Class

Can we make a database connection class which allows us just change the configuration file, and then use the database? I did the prototype of this class which is very simple. But the idea is good, always use a very simple jar file to get setup database which can then do SQL query operations.

package com.programcreek.db;
import java.sql.*;
 
public class DB {
 
	private Connection conn = null;
 
	public DB(String url, String user_name, String password) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user_name, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	public ResultSet runSql(String sql) throws SQLException {
		Statement sta = conn.createStatement();
		return sta.executeQuery(sql);
	}
 
	@Override
	protected void finalize() throws Throwable {
		if (conn != null && !conn.isClosed()) {
			conn.close();
		}
	}
 
}

Here is the code to call the DB class: 

package com.programcreek.test;
 
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
 
import com.programcreek.db.DB;
 
public class Main {
 
	public static void main(String []args){
 
		// to read url, username, password from configuration file
		Properties configFile = new Properties();
		String url = "";
		String user_name = "";
		String password = "";
		String database = "";
		try {
			configFile.load(Main.class.getClassLoader().getResourceAsStream("config.properties"));
			url = configFile.getProperty("url");
			database = configFile.getProperty("database");
			user_name = configFile.getProperty("user_name");
			password = configFile.getProperty("password");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 
		//instantiate a DB object
		DB db = new DB(url + database, user_name, password);
		try {
			ResultSet rs = db.runSql("select * from user");
			while(rs.next()){
				System.out.println(rs.getString("user_name"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

This is the prototype of this idea, a complete database connection class should be able to:

1) connect different database such as SQLServer, Accsss, etc

2) has function as runDB(), which can do ADD, UPDATE, DELETE operations using an array.  Take update for example, runDB(UPDATE, data), in which data is a mapping array.

3) has logging function using what I have showed in my previous post.

Category >> Database  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

Leave a comment

*