[CODE]package com.simon.db;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.text.SimpleDateFormat;
import static java.lang.System.out;
import static java.lang.System.err;
//import sun.jdbc.odbc.JdbcOdbcDriver; //连SQL的时候用到这个桥接驱动
public class DBConnection {
public static Connection con;
public DBConnection() {}
public static Connection getConnection() throws
IOException, SQLException {
// TODO Auto-generated constructor stub
ResourceBundle rb = ResourceBundle.getBundle("db");
try {
//String DriverName = rb.getString("db.mysqldriver");
//DriverName = com.MySQL.jdbc.Driver;
//Class.forName(DriverName);
Class.forName("org.gjt.mm.mysql.Driver");
String user = rb.getString("db.mysqluser");
String password = rb.getString("db.mysqlpassword");
String url = rb.getString("db.mysqlurl");
//解决中文字符的问题
//url += "?useUnicode=true&characterEncoding=gb2312";
con = DriverManager.getConnection(url,user,password);
return con;
} catch(ClassNotFoundException cnfExc) {
out.println(cnfExc.getMessage());
cnfExc.printStackTrace();
} catch(SQLException sqlExc) {
out.println(sqlExc.getMessage());
sqlExc.printStackTrace();
} catch(Exception e) {
out.println(e.getMessage());
e.printStackTrace();
}
err.println("出异常啦,返回回值!"); //测试连接成功没的,下同。
return null;
}
//下面是用数据源桥接驱动连接的SQL。
/*public static Connection getConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
DriverManager.registerDriver(new JdbcOdbcDriver());
Connection conn = DriverManager.getConnection("jdbc:odbc:JDBC");
return conn;
} catch(ClassNotFoundException cnfExc) {
out.println(cnfExc.getMessage());
cnfExc.printStackTrace();
} catch(SQLException sqlExc) {
out.println(sqlExc.getMessage());
sqlExc.printStackTrace();
} catch(Exception e) {
out.println(e.getMessage());
e.printStackTrace();
}
//err.println("123");
return null;
} */
//sql语句执行方法,暂时没发现有什么用(结构也有点问题),主要是测试时用的。
public static void execute(String SQLCommand) {
try {
Statement stmt = getConnection().createStatement();
ResultSet rs = stmt.executeQuery("select * from users");
while(rs.next()) {
out.print(rs.getString(1));
out.print(rs.getString(2));
out.print(rs.getString(3));
}
return;
} catch(IOException ioExc) {
out.println(ioExc.getMessage());
ioExc.printStackTrace();
} catch(SQLException sqlExc) {
out.println(sqlExc.getMessage());
sqlExc.printStackTrace();
}
err.println("出异常啦,返回回值!");
}
public void close() {
try {
this.close();
} catch(Exception e) {
out.println(e.getMessage());
e.printStackTrace();
}
}
//这个方法在UTIL中也有一个,应该是把它放到那里的。
public static String getTime() {
long timer = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return sdf.format(timer);
}
/**
* @param args
*/
public static void main(String[] args) throws Throwable{
// TODO Auto-generated method stub
out.println(getConnection());
//out.print(getTime());
execute("select * from users");
}
}[/CODE]
这是DBConnection类