使用JDBC连接数据库并且调用存储过程和执行SQL语句

时间:2021-03-02 14:06:35

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;
}
}