basedao(连接数据库)

package poll.dao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;






public class BaseDAO {

private static final String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String url="jdbc:sqlserver://localhost:1433;databaseName=POLL_DB";
public static Connection getCon(){
Connection con = null;
try {
con = null;
Class.forName(driver);
con = DriverManager.getConnection(url,"sa","123");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//无结果有参数
public static boolean runUpdateSql(String sql, Object[] params){
Connection con=null;
PreparedStatement pst = null;
try{
con = getCon();
pst = con.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1, params[i]);
}
pst.executeUpdate();
return true;
}catch(Exception e){
e.printStackTrace();
}finally{
try{
pst.close();
con.close();
}catch(Exception e){e.printStackTrace();
}
}
return  true;
}
//you结果,wu参数
public static Result runSelectSql(String sql){
Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
Result result = null;
//得到连接
con = getCon();

//rst = pst.execute();execute是boolean类型
try {
pst = con.prepareStatement(sql);
rst = pst.executeQuery();
result = ResultSupport.toResult(rst);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
rst.close();
pst.close();
con.close();
}catch(Exception e){e.printStackTrace();
}
}

return result;

}





}
posted @ 2022-04-08 18:02  oceanyang  阅读(76)  评论(0编辑  收藏  举报