3.写一段JDBC连接数据库的代码,CONNECTION最后要关闭。

 我来答
raymond418
推荐于2016-03-20 · TA获得超过169个赞
知道小有建树答主
回答量:310
采纳率:0%
帮助的人:201万
展开全部
public Connection getConnection() {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

return DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=test","sa","");
} catch (ClassNotFoundException e) {

throw new DaoException("加载驱动程序失败",e);
} catch (SQLException e) {
throw new DaoException("数据库连接失败",e);
}

}

public void close(ResultSet rs, Statement stmt, Connection conn) {
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
summer_84529
2009-02-26
知道答主
回答量:11
采纳率:0%
帮助的人:3.9万
展开全部
public class Conn {

private Connection connection = null;
static String username = "scott";
static String password = "tiger";
static String classStr = "oracle.jdbc.driver.OracleDriver";
static String urlStr = "jdbc:oracle:thin:@localhost:1521:myoracle";

public Conn() throws ClassNotFoundException, SQLException {
Class.forName(classStr);
connection = DriverManager.getConnection(urlStr,
username, password);
}

public Connection getConnection() {
return connection;
}

/*这是一个专门用来关闭程序中所有Connection的静态方法,包括其子接口,下面有关于对这个方法的调用类的举例*/
public static void close(ResultSet resultSet,
PreparedStatement prepraredStatement,
CallableStatement callableStatement, Statement statement,
Connection connection) throws SQLException {
if (resultSet != null){
resultSet.close();
}
if (prepraredStatement != null){
prepraredStatement.close();
}
if (callableStatement != null){
callableStatement.close();
}
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
}

public class Database {

private Connection connection = null;

public Database() throws ClassNotFoundException, SQLException {
connection = new Conn().getConnection();
}

public int login(LoginDTO loginDTO) throws SQLException {
int flag = 0;
String sqlStr = "begin ?:=useroption.login(?,?); end;";
CallableStatement callableStatement = connection.prepareCall(sqlStr);
callableStatement.registerOutParameter(1, java.sql.Types.INTEGER);
callableStatement.setString(2, loginDTO.getJTextField_username());
callableStatement.setString(3, loginDTO.getJPasswordField_password());
callableStatement.execute();
flag = callableStatement.getInt(1);
Conn.close(null, null, callableStatement, null, connection);
return flag;
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式