JDBC 의 일반적인 첨삭 검사 작업(MySQL,반사)
데이터베이스 연결 가 져 오기
url=jdbc:mysql://localhost:3306/database
user=jdbctest
password=jdbctest123
className=com.mysql.cj.jdbc.Driver
public static Connection getConnection(){
Connection conn = null;
try {
// 1. Load properties file
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties props = new Properties();
props.load(is);
// 2. Get four elements
String url = props.getProperty("url");
String user = props.getProperty("user");
String password = props.getProperty("password");
String className = props.getProperty("className");
// 3. Register Driver class
Class.forName(className);
// 4. Get connector
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
데이터베이스 업데이트:첨삭 수정
/**
* Update: update, insert, delete
*
* @param sql your SQL statement
* @param objs parameters in SQL replace placeholder
*/
public void update(String sql, Object... objs) {
Connection conn = null;
PreparedStatement ps = null;
try {
// Get connector
conn = JDBCUtils.getConnection();
// PreparedStatement for precompiling sql statement
ps = conn.prepareStatement(sql);
// Replace the placeholders
for (int i = 0; i < objs.length; i++) {
ps.setObject(i + 1, objs[i]);
}
// Execute sql statement
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close resources
JDBCUtils.closeResources(conn, ps);
}
}
데이터베이스 조회(반사)
/**
* Using it for SQL query, and returns a list including objects
* @param Generics class
* @param clazz pojo for your table
* @param sql sql statement
* @param objs parameter used by replacing placeholder
* @return a list including all objects you get
*/
public <T> List<T> query(Class<T> clazz, String sql, Object... objs) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<T> list = null;
try {
// 1. Get connector
conn = JDBCUtils.getConnection();
// 2. PreparedStatement to precompile SQL statement
ps = conn.prepareStatement(sql);
// 3. Repalce all placeholder
for (int i = 0; i < objs.length; i++) {
ps.setObject(i + 1, objs[i]);
}
// 4. Excute SQL statement
rs = ps.executeQuery();
// 5. Meta data is easier to process reslut set
ResultSetMetaData rsmd = rs.getMetaData();
int ccount = rsmd.getColumnCount();
list = new ArrayList<T>();
while (rs.next()) {
T t = clazz.newInstance();
for (int i = 0; i < ccount; i++) {
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
// Using reflect to set the value for every column
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
}
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResources(conn, ps, rs);
}
return list;
}
총결산
전체 코드
JDBCUtils
/**
*
* @author Master_Joe
*
*/
public class JDBCUtils {
/**
* @return SQL Connectors
*/
public static Connection getConnection(){
Connection conn = null;
try {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties props = new Properties();
props.load(is);
String url = props.getProperty("url");
String user = props.getProperty("user");
String password = props.getProperty("password");
String className = props.getProperty("className");
Class.forName(className);
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* Close resources connector and statement
* @param conn SQL connector
* @param statement
*/
public static void closeResources(Connection conn, Statement statement) {
try {
if (conn != null) {
conn.close();
}
if (statement != null) {
statement.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Close resources including Connectors, Statement and ResultSet
* @param conn SQL connector
* @param statement
* @param rs ResultSet
*/
public static void closeResources(Connection conn, Statement statement, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Update & Query
업데이트 및 조회 작업 을 실현 하 였 습 니 다.
/**
* Update & Query for SQL
*
* @author Master_Joe
*
*/
public class Operating {
@Test
public void testOperating() {
String sql = null;
Object[] objs = new Object[] {};
update(sql, objs);
List<Operating> list = query(Operating.class, sql, objs);
list.forEach(System.out::println);
}
/**
* Update: update, insert, delete
*
* @param sql
* @param objs
*/
public void update(String sql, Object... objs) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < objs.length; i++) {
ps.setObject(i + 1, objs[i]);
}
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResources(conn, ps);
}
}
/**
* Using it for SQL query, and returns a list including objects
*
* @param Generics class
* @param clazz pojo for your table
* @param sql sql statement
* @param objs parameter used by replacing placeholder
* @return a list including all objects you get
*/
public <T> List<T> query(Class<T> clazz, String sql, Object... objs) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<T> list = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < objs.length; i++) {
ps.setObject(i + 1, objs[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int ccount = rsmd.getColumnCount();
list = new ArrayList<T>();
while (rs.next()) {
T t = clazz.newInstance();
for (int i = 0; i < ccount; i++) {
Object columnValue = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
// reflect to set the value for every column
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
}
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
잘못 이 있 으 면 연락 주세요.
작성 자 메 일:[email protected]
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
TIL# 157 ubuntu에서 mariadb 버전 바꾸기로컬에서는 잘 동작했던 recursive 쿼리가 동작하지 않아 원인을 찾아보니 ubuntu의 마리아디비가 버전이 더 낮아 호환되지 않아서 에러가 발생했던 거였다. 현재 로컬에서 사용하고 배포하여도 사용할 마리아디비 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.