Backend/JAVA

JDBC를 이용한 DB 연결 (Connetion 생성)

dddzr 2023. 4. 24. 12:08
String dbType = prjInfo.getDbType().toUpperCase();
String url = "";
try {
	if (dbType.equals("ORACLE")) {
		url = "jdbc:oracle:thin:@" + prjInfo.getIp() + ":" + prjInfo.getPort() + ":" + prjInfo.getSid();
	} else if (dbType.equals("MARIADB")) {
		url = "jdbc:mariadb://" + prjInfo.getIp() + ":" + prjInfo.getPort() + "/" + prjInfo.getDbName()
			+ "?characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true";
	} else if (dbType.equals("MSSQL")) {
		url = "jdbc:sqlserver://" + prjInfo.getIp() + ";databaseName=" + prjInfo.getDbName();
	}
		con = DriverManager.getConnection(url, prjInfo.getDbId(), prjInfo.getDbPassword());
} catch (SQLException e1) {
	e1.printStackTrace();
}            
String sql = "SELECT * FROM TABLE WHERE NAME = ?";
PreparedStatement ps = con.prepareStatement(sql);
//ps.setString(1, param1);
//ResultSet rs = ps.executeUpdate(); //insert, update, delete등 리턴값이 필요 없는 쿼리문
ResultSet rs = ps.executeQuery(); //select 등 리턴값이 필요한 쿼리

// 리턴값 이용
while(rs.next()){
    String name = rs.getString("name");
 }