2007年10月31日 星期三

寫一支簡單的 java程式 來取得資料庫連線(getConnection)

package com.test.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
*
* @author jimmy
*/
public class simpleConnection {


Connection conn = null;

simpleConnection(){}


//get connection
public Connection getConnection(){
try {

Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ICPS","root", "");
/*
利用properties
Properties props = new Properties ();
props.put("user", "root");
props.put("root", "");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ICPS",props);
*/
System.out.println("=================== getconnection Success ======================");
}catch(Exception e){
e.printStackTrace();
System.out.println("=================== getconnection error ======================");
}
return conn;
}


//close connection
public void closeConnection(){
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

//execute query
public void sqlexecuteQuery(Connection conn){

String sql = "select * from icpsuser";
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);

while(rs.next()){
System.out.println(rs.getString("userid")+"/"+ rs.getString("username"));
}

} catch (SQLException ex) {
ex.printStackTrace();
}

}


public void run(){
Connection conn = this.getConnection();
this.sqlexecuteQuery(conn);
this.closeConnection();
}

public static void main(String[] arg){

simpleConnection sc = new simpleConnection();
sc.run();
}

}

沒有留言: