java使用url和tns两种方式连接数据库执行存储过程
1.url方式(连接数据库并执行一个查询):
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Statement statement;
ResultSet rs;
Connection conn;
String sql;
/**
db.driveName=oracle.jdbc.driver.OracleDriver
db.username=user
db.pwd=pwd
db.url=jdbc:oracle:thin:@****:1521:ywxx
*/
String userName = PropertiesUtil.getString("db.username");
String userPwd = PropertiesUtil.getString("db.pwd");
Class.forName(PropertiesUtil.getString("db.driveName"));
String dbURL = PropertiesUtil.getString("db.url");
conn = DriverManager.getConnection(dbURL, userName, userPwd);
statement = conn.createStatement();
sql = "select AA from task;";
String aa;
rs = statement.executeQuery(sql);
while (rs.next()) {
aa = rs.getString("AA");
System.out.println(aa);
}
rs.close();
conn.close();
}
2.tns需要根据名称去查找对应的信息,所以要配置一个查找路径(连接数据库并执行一个存储过程):
public static void main(String[] args) throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException { /** db.driveName=oracle.jdbc.driver.OracleDriver db.username=user db.pwd=pwd db.tns=orcl */ String userName = PropertiesUtil.getString("db.username"); String userPwd = PropertiesUtil.getString("db.pwd"); String dbURL = "jdbc:oracle:thin:@" + PropertiesUtil.getString("db.tns"); Class.forName(PropertiesUtil.getString("db.driveName")); Connection conn; CallableStatement callableStatement; System.setProperty("oracle.net.tns_admin", System.getenv("ORACLE_HOME") + File.separator + "NETWORK" + File.separator + "ADMIN"); System.out.println(System.getProperty("oracle.net.tns_admin")); Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection(dbURL, userName, userPwd); callableStatement = conn.prepareCall("{call pro_name}"); callableStatement.execute(); callableStatement.close(); conn.close(); }