- 论坛徽章:
- 0
|
- import java.sql.*;
- public class Helper {
- private Helper() {
- }
- public static Connection getConnection() {
- try {
- Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
- String url = "";
- Connection con = DriverManager.getConnection(url, "gongfuxuan",
- "password");
- return con;
- }
- catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Error while get database Connection");
- }
- }
- public static ResultSet query(String sql) {
- Connection con = getConnection();
- ResultSet rs = null;
- try {
- Statement st = con.createStatement();
- rs = st.executeQuery(sql);
- if (st != null) {
- st.close();
- }
- if (con != null) {
- con.close();
- }
- }
- catch (SQLException e) {
- System.out.println("SQL Error,code: " + e.getErrorCode() + ", state:" +
- e.getSQLState() + "when execute sql:" + sql);
- }
- return rs;
- }
- public static boolean execute(String sql) {
- Connection con = getConnection();
- boolean result = false;
- try {
- Statement st = con.createStatement();
- result = st.execute(sql);
- if (st != null) {
- st.close();
- }
- if (con != null) {
- con.close();
- }
- }
- catch (SQLException e) {
- System.out.println("SQL Error,code: " + e.getErrorCode() + ", state:" +
- e.getSQLState() + "when execute sql:" + sql);
- }
- return result;
- }
- public static long Update(String sql) {
- Connection con = getConnection();
- long result = -1L;
- try {
- Statement st = con.createStatement();
- result = st.executeUpdate(sql);
- if (st != null) {
- st.close();
- }
- if (con != null) {
- con.close();
- }
- }
- catch (SQLException e) {
- System.out.println("SQL Error,code: " + e.getErrorCode() + ", state:" +
- e.getSQLState() + "when execute sql:" + sql);
- }
- return result;
- }
- }
复制代码 |
|