วันจันทร์ที่ 27 มิถุนายน พ.ศ. 2554

การ Connect แบบ JDBC โดยใช้ Java


การ Connect แบบ JDBC โดยใช้  Java

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCDriverInformation {
      static String userid="root";
      static String password = "password";
      static String url = "jdbc:mysql://127.0.0.1:3306/ecom";    
      static Connection con = null;
      public static void main(String[] args) throws Exception {
          Connection con = getMySqlJDBCConnection();
          if(con!= null){
             System.out.println("Got Connection.");
             DatabaseMetaData meta = con.getMetaData();
             System.out.println("Driver Name : "+meta.getDriverName());
             System.out.println("Driver Version : "+meta.getDriverVersion());
             System.out.println("Got Connection success....");
          }else{
                System.out.println("Could not Get Connection");
          }
      }

      public static Connection getMySqlJDBCConnection(){

            try {
                  Class.forName("com.mysql.jdbc.Driver");  
            } catch(java.lang.ClassNotFoundException e) {
                  System.err.print("ClassNotFoundException: ");
                  System.err.println(e.getMessage());
            }

            try {
               con = DriverManager.getConnection(url, userid, password);
            } catch(SQLException ex) {
                  System.err.println("SQLException: " + ex.getMessage());
            }

            return con;
      }

}

// Output >>
Got Connection.
Driver Name : MySQL-AB JDBC Driver
Driver Version : mysql-connector-java-5.0.7 ( $Date: 2007-03-09 22:13:57 +0100 (Fri, 09 Mar 2007) $, $Revision: 6341 $ )
Got Connection success....

ขอให้สนุกกับการทดลองนะครับ http://java-thai-talk.blogspot.com/