Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts

Wednesday, December 21, 2011

Database Access in Java (JDBC Example)

Accessing and retrieving data from a database is very simple.
First of all you need to add the DB driver(.jar) to your project. After that you can use below code.
In this example I am using mySql database.
//load DB driver
Class.forName("com.mysql.jdbc.Driver");
//this is the connection string
String connString 
   = "jdbc:mysql://localhost:3306/mydb?user=root&password=";  
//Create connection
Connection con = DriverManager.getConnection(connString);
//Create a Statement object using connection
Statement statement = con.createStatement();
//Execute the SQL statement and get the results as a Resultset(Note that the name of the table is 'employee')
ResultSet resultSet = statement.executeQuery("select * from 
           employee");
//Now we can iterate through the resultSet 
while(resultSet.next()){
//following method returns the value in Object type. 
//'name_full' is the column name
  Object o = resultSet.getObject("name_full");
  System.out.println(o);
//following method returns the value in String type.
 String s = resultSet.getString("name_full");
}
Note that you can remove above first two lines of the code and replace third line from below line to get the same result.
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");