use try-with-resource style for sql queries

This commit is contained in:
Sola
2015-11-22 23:23:39 +08:00
parent 8959b33a04
commit 5d01a9669a
2 changed files with 4 additions and 16 deletions

View File

@@ -2,8 +2,6 @@ package love.sola.netsupport.sql;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* ***********************************************
@@ -25,8 +23,4 @@ public class SQLCore {
}
}
public static void free(Connection conn) {
if (conn != null) try { conn.close(); } catch (SQLException e) { }
}
}

View File

@@ -24,9 +24,7 @@ public class TableUser extends SQLCore {
public static final String COLUMN_WECHAT = "wechat";
public static User getUserByName(String name) {
Connection conn = null;
try {
conn = ds.getConnection();
try (Connection conn = ds.getConnection()) {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user_info WHERE name=?");
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
@@ -38,15 +36,12 @@ public class TableUser extends SQLCore {
ISPType.fromId(rs.getInt(COLUMN_ISP)),
rs.getString(COLUMN_WECHAT));
}
} catch (SQLException e) {
} finally { free(conn); }
} catch (SQLException e) { }
return null;
}
public static User getUserById(int id) {
Connection conn = null;
try {
conn = ds.getConnection();
try (Connection conn = ds.getConnection()) {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user_info WHERE id=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
@@ -58,8 +53,7 @@ public class TableUser extends SQLCore {
ISPType.fromId(rs.getInt(COLUMN_ISP)),
rs.getString(COLUMN_WECHAT));
}
} catch (SQLException e) {
} finally { free(conn); }
} catch (SQLException e) { }
return null;
}