日期:2014-05-20 浏览次数:21052 次
package reader;
import java.sql.*;
public class DBConnector {
static{
try{
Class.forName("org.gjt.mm.mysql.Driver");
}
catch (ClassNotFoundException e) {
System.err.println("ClassNotFoundException in Class- DBConnector");
}
}
public static Connection getConnection(String host,String dbName,String username,String password){
Connection connection = null;
try{
String url = "jdbc:mysql://"+host+"/"+dbName+"?useUnicode=true&characterEncoding=UTF-8";
connection = DriverManager.getConnection(url,username,password);
}
catch(SQLException e){
System.err.print(e);
}
return connection;
}
public static void main(String[] args){
Connection conn = DBConnector.getConnection("localhost", "dbname", "root", "");
if(conn != null){
System.out.println("conn is not null");
}
System.out.println("OK");
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = getConnection("127.0.0.1:3306", "dbname", "root", "");
String sql = "SELECT * FROM";
Statement state;
ResultSet rs = null;
PrintWriter out = response.getWriter();
if(conn != null){
try {
state = conn.createStatement();
rs = state.executeQuery(sql);
while(rs.next()){
out.println(rs.getString(1)+rs.getString(2)+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
else{
out.println("Conn is null");
}
}