使用JDBC連線資料庫並且呼叫儲存過程和執行SQL語句
阿新 • • 發佈:2019-02-19
JDBC呼叫資料庫:
package com.hthk.iisz.util; import java.sql.Connection; import java.sql.DriverManager; public class SqlServerConnectionzUtil { public static Connection getConnection() { String driverName = "oracle.jdbc.driver.OracleDriver"; String dbURL = "jdbc:oracle:thin:@172.25.15.139:1526:atomsu"; String userName = "atoms"; String userPwd = "abc123"; Connection dbConn = null; try { Class.forName(driverName); dbConn = DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("連線資料庫成功"); return dbConn; } catch (Exception e) { e.printStackTrace(); System.out.print("連線失敗"); } return dbConn; } }
連線好資料庫後呼叫其儲存過程和執行SQL語句:
package com.hthk.iisz.dao; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import com.hthk.iisz.util.SqlServerConnectionzUtil; public class TcnConnectDatabaseDao { Connection conn; PreparedStatement stmt; ResultSet rs; public int getConnection(String id, String phone) throws SQLException { try { Connection conn = SqlServerConnectionzUtil.getConnection();// 得到jdbc // Connection CallableStatement cstmt = conn .prepareCall("{call mytv_super_pkg.CHECK_STATUS(?,?,?)}");// 呼叫儲存過程 cstmt.setString(1, id);// in引數 cstmt.setString(2, phone);// in引數 System.out.println(id+"--------"+phone); cstmt.registerOutParameter(3, Types.INTEGER);// out引數 cstmt.execute(); return cstmt.getInt(3);// 得到3位置的out值 } catch (SQLException e) { e.printStackTrace(); return 0; } } public String getExpiryDate(String id) throws SQLException { try { Connection conn = SqlServerConnectionzUtil.getConnection();// 得到jdbc // Connection Statement stmt = conn.createStatement(); ResultSet rs = stmt .executeQuery("select expiry_date from mytv_super_offer where random_id=" + id);// 執行SQL語句 while (rs.next()) { return rs.getString("expiry_date"); } } catch (SQLException e) { e.printStackTrace(); return null; } finally { // 關閉資料庫,一般是後開的先關,對應上面 try { if (rs != null) { // 如果rs一開始就是null的話,如果不判斷就一直出SQL異常,所以應該先判斷一下 rs.close(); } if (stmt != null) { // 如果stmt一開始就是null的話,如果不判斷就一直出SQL異常,所以應該先判斷一下 stmt.close(); } if (conn != null) { // 如果conn一開始就是null的話,如果不判斷就一直出SQL異常,所以應該先判斷一下 conn.close(); } } catch (SQLException se) { se.printStackTrace(); } } return null; } }