13 December 2010

java JDBC MySQL Connect

java JDBC MySQL Connect Table: test

ID Name
1 A
2 B
3 C

import java.io.File;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Main {   
    public static void main(String args[]) {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost","USERNAME", "PASSWORD");
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select * from test");
            int count = 0;
            while(rs.next())
            {
                System.out.println("ID : " + rs.getString(0));
                System.out.println("NAME : " + rs.getString(1));
                count++;
            }
            System.out.println("sum = "+count);
            
            } catch(Exception e) {
            e.printStackTrace();
            System.out.println("Exception: " + e.getMessage());
            } finally {
            try {
                if(con != null)
                con.close();
        } catch(SQLException e) {}
        }
    }
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Blog by Chagridsada Boonthus | http://chagridsada.blogspot.com/