2007年3月18日 星期日

[Java] 與 MySQL 溝通




class dbMySQL{

final private String dbDriver = "com.mysql.jdbc.Driver";

public String dbAddress = null;

public String dbName = null;

public String dbUrl = null;

public String dbUser = null;

public String dbPasswd = null;

dbMySQL(String db_url,String db_name,String db_user,String db_passwd){

setupDB(db_url,db_name,db_user,db_passwd);

}

public void setupDB(String url,String dbname,String dbuser,String dbpasswd){

dbAddress = url;

setupDBUser(dbuser,dbpasswd);

setupDBName(dbname);

}

private void setupDBName(String dbname){

dbName = dbname;

//dbUrl = "jdbc:mysql://"+dbAddress+":3306/"+dbName+"?useUnicode=true&characterEncoding=Big5";

dbUrl = "jdbc:mysql://"+dbAddress+":3306/"+dbName+"?useUnicode=true&characterEncoding=utf-8";

}

private void setupDBUser(String dbuser,String dbpasswd){

dbUser = dbuser;dbPasswd = dbpasswd;

}

public java.sql.ResultSet SQLquery(String cmd){

try{

Class.forName(dbDriver);

java.sql.Connection con = java.sql.DriverManager.getConnection(dbUrl, dbUser, dbPasswd);

if(!con.isClosed()){

java.sql.PreparedStatement pstmt = con.prepareStatement(cmd);

java.sql.ResultSet rs = pstmt.executeQuery();

con.close();

return rs;

}

}catch(java.lang.ClassNotFoundException e){

e.printStackTrace();//Can't find: "+dbDriver+"

}catch(java.sql.SQLException e){

e.printStackTrace();

}

return null;

}

public String SQLupdate(String cmd){

try{

Class.forName(dbDriver);

java.sql.Connection con = java.sql.DriverManager.getConnection(dbUrl, dbUser, dbPasswd);

if(!con.isClosed()){

java.sql.PreparedStatement pstmt = con.prepareStatement(cmd);

pstmt.executeUpdate();

con.close();

return "OK";

}

}catch(java.lang.ClassNotFoundException e){

e.printStackTrace();

}catch(java.sql.SQLException e){

e.printStackTrace();

}

return "NO";

}

}



/* 使用方式
class Test{
private dbMySQL DB = null;
public Test(String db_url,String db_name,String db_user,String db_passwd){
DB = new dbMySQL(db_url,db_name,db_user,db_passwd);
DB.SQLupdate("DELETE From `MySQL_Table_Name`");

java.sql.ResultSet SQLrs =null;
SQLrs = DB.SQLquery("SELECT * FROM `MySQL_Table_Name`");
if(SQLrs != null){
while(SQLrs.next()){
//因為是用 UTF-8 存的, 所以讀出來要轉成 Big5
String data = new String( SQLrs.getString("欄位名字").getBytes(), "Big5");
}
}
}
}
*/



沒有留言:

張貼留言