What Is JDBC
What Is JDBC
• }
Continued…
• //STEP 6: Clean-up environment
• rs.close();
• stmt.close();
• conn.close();
• }catch(SQLException se){
• //Handle errors for JDBC
• se.printStackTrace();
• }catch(Exception e){
• //Handle errors for Class.forName
• e.printStackTrace();
• }finally{
• //finally block used to close resources
Continued…
• try{
• if(stmt!=null)
• stmt.close();
• }catch(SQLException se2){
• }// nothing we can do
• try{
• if(conn!=null)
• conn.close();
• }catch(SQLException se){
• se.printStackTrace();
• }//end finally try
• }//end try
Continued…
• System.out.println("Goodbye!");
• }//end main
• }//end FirstExample
• Now let us compile above example as follows:
• C:\>javac FirstExample.java
• C:\>
Continued…
• When you run FirstExample, it produces following result:
• C:\>java FirstExample
• Connecting to database...
• Creating statement...
• ID: 1
• Name: Abebe
• Mark:80
• ID: 2
• Name: kebede
• Mark: 90
• C:\>
Example2
• import java.sql.*;
• public class SqlTest
• {
• public static void main(String[] args)
• {
• try
• {
• // Step 1: Make a connection
• // Load the driver
• Class.forName("com.mysql.jdbc.Driver");
• // Get a connection using this driver
• String url = "jdbc:mysql://localhost/user";
• String dbUser = "root";
• String dbPassword = "9818";
Continued..
• Connection con = DriverManager.getConnection(url, dbUser, dbPassword);
• Statement stmt = con.createStatement();
• String sql= "SELECT * FROM student";
• ResultSet rs = stmt.executeQuery(sql);
• int id;
• String name;
• int marks;
• while (rs.next())
• {
• id = rs.getInt("sid");
• name = rs.getString("sname");
• marks = rs.getInt("smarks");
Continued…
• System.out.println("Id= "+id+"name = " + name + " marks = " + marks);
• }
• stmt.close();
• con.close();
• }
• catch(ClassNotFoundException ex1)
• {
• System.out.println(ex1);
• }
• catch(SQLException ex2)
• {
• System.out.println(ex2);
• }
• }
• }
Continued…
• Now let us compile above example as follows:
• C:\>javac SqlTest.java
• C:\>java SqlTest
• ID = 1 name =Abebe marks= 80
• ID = 2 name = Kebede marks=90
• C:\>