Sunday, February 22, 2009

Program to Connect Mysql Database in Java

The program connects mysql database in java. It assumes that the database named test exist in the local computer and mysql.jar is loaded in the JRE system library. It retrives and displays the name of the employee from the database.

package pack;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class MysqlConn {
static String user = "mahesh";
static String password = "prajap";
static String url = "jdbc:mysql://localhost/test";

public static Connection dbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection conn = DriverManager.getConnection(url, user,
password);
return conn;
} catch (Exception ms) {
ms.printStackTrace();
return null;
}
}

public static void main(String args[]) {
MysqlConn conn = new MysqlConn();
conn.getEmp();
}

public void getEmp() {

Connection conn = MysqlConn.dbConnect();
String queryStr = "select emp_id,emp_name from emp";

try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(queryStr);
while(rs.next()){
System.out.println("The employee is: "+rs.getString(2));
}

} catch (Exception ms) {
ms.printStackTrace();

}
}

}

No comments: