opencodez

Connect to MySQL in Java

Itxs been too long, I didnt get time to post anything OpenSource.
So here I am again with one simple class Database, to connect to MySQL in Java.
You can use this class in 2 ways x

  1. Specifying user,pwd and database name to connect
  2. Specifying connection ID and class will load rest of the variables from CONFIG file

Here I will post the Database class only, class to read config file and loading properties will be posted in different post.

The Database

import java.sql.*;

public class Database
{
	Connection conn;
	Statement stmt;
	PreparedStatement pstmt;
	ResultSet rs;
	Config cfg;
	int affectedRows;

	/*Reading From CFG*/
	String dbuser,dbpwd,dbname,dbserver;

	public Database(){
	}

	public Database(String database, String user,String pwd)
	{
		this.affectedRows = 0;
		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(
			"jdbc:mysql://localhost:3306/"+database, user
			, pwd);
			stmt = conn.createStatement();
		}
		catch (Exception e){
			e.printStackTrace();
		}
	}

	public Database(String dbid)
	{
		cfg = new Config();
		this.dbname   = cfg.getProperty("mStrName"+dbid);
		this.dbuser   = cfg.getProperty("mStrUser"+dbid);
		this.dbpwd    = cfg.getProperty("mStrPwds"+dbid);
		this.dbserver = cfg.getProperty("mStrHost"+dbid);

		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(
			"jdbc:mysql://localhost:3306/"+this.dbname, this.dbuser
			, this.dbpwd);
			stmt = conn.createStatement();
		}
		catch (Exception e){
			e.printStackTrace();
		}
	}

	public ResultSet query(String qry)
	{
		try{
			rs = this.stmt.executeQuery(qry);
		}catch(SQLException se){
			System.out.println("Error : " + se.getMessage());
		}
		return rs;
	}

	public int update(String qry)
	{
		int count = 0;
		try{
			count = this.stmt.executeUpdate(qry);
		}catch(Exception se){
			System.out.println("Error : " + se.getMessage());
		}
		return count;
	}
}

And here is how we are going to use this class:

Database db = new Database("mydb","myuser","mypwd");
//simple query
ResultSet rs = db.query("SELECT * FROM mytable");

Now you can traverse record rs set in a way you wantx

//update query
int affected = db.update("DELETE FROM mytable");

We will shortly see how we are going to use Config class and its usage.

Summary

So now yo have seen how its easy to connect to MySQL in Java. I hope you find this example useful and you can use in any of your assignment or project.