Saturday 25 December 2010

Java: JDBC basics

JDBC is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database.


How it works?
1.First you should specify sql driver
Class.forName("com.mysql.jdbc.Driver");

2.Next url to your sql server
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "userName", "userPassword");

3.And finally execute query using Statement or PreparedStatement

Example
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

class jdbcTest {
 public static void main(String args[]) {
  try {
   //connecting
   Class.forName("com.mysql.jdbc.Driver");
   String url = "jdbc:mysql://localhost:3306/dbName";
   Connection con = DriverManager.getConnection(url, "root", "");
   List groups = new ArrayList();
   
   //using Statement to select
   Statement stmt = null;
   ResultSet rs = null;
   try {
    stmt = con.createStatement();
    rs = stmt
      .executeQuery("SELECT group_id, groupName FROM groups");
    while (rs.next()) {     
       Group gr = new Group(); 
       gr.setGroupId(rs.getInt(1));
       gr.setNameGroup(rs.getString(2));      
       groups.add(gr);      
    }
    
    
   //using prepared Statement to insert 
    PreparedStatement stmt2 = null;
          try {
              stmt = con.prepareStatement(
                      "INSERT INTO groups " +
                      "(group_id, groupName) " +
                      "VALUES (?, ?)");
              stmt2.setInt(1, group.getId());
              stmt2.setString(2, group.getName());          
              stmt2.execute();
   } finally {
    if (rs != null) {
     rs.close();
    }
    if (stmt != null) {
     stmt.close();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  } 
 }
}

No comments:

Post a Comment