2011年8月16日 星期二

MySQL連線 練習

import java.sql.*;

public class DBConnectionDemo {
    public static void main(String[] args) {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/My108";
        String user = "root";
        String password = "1234";
        Connection conn = null;
        Statement stmt = null;

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,user, password);

            if(conn != null && !conn.isClosed()) {
                System.out.println("資料庫連線測試成功!");
            }

        }
        catch(ClassNotFoundException e) {
            System.out.println("找不到驅動程式類別");
            e.printStackTrace();
        }
        catch(SQLException e) {
            e.printStackTrace();
        }finally{
            try{
                if(stmt!=null){stmt.close();}
                if(conn!=null){conn.close();}
            }catch(SQLException e){
                System.err.println(e);
            }
        }
    }
}

沒有留言 :

張貼留言