Open BKJang opened 4 years ago
JDBC
๋ JAVA
๋ฅผ ์ด์ฉํด์ ๋ฐ์ดํฐ ๋ฒ ์ด์ค ์ ์๊ณผ SQL ์คํ ๋ฐ ๊ทธ์ ๋ฐ๋ฅธ ๊ฒฐ๊ณผ ๋ฐ์ดํฐ์ ํธ๋ค๋ง์ ์ ๊ณตํ๋ ๋ฐฉ๋ฒ๊ณผ ์ ์ฐจ์ ๋ํ ๊ท์ฝ์ด๋ค. ์ฆ, ์ฝ๊ฒ ๋งํด JAVA
๋ฅผ ์ด์ฉํด ๊ตฌํํ ์ ํ๋ฆฌ์ผ์ด์
๋ด์์ SQL๋ฌธ์ ์คํํ๊ธฐ ์ํด ๋ง๋ค์ด์ง API๋ผ๊ณ ํ ์ ์๋ค.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
import java.sql.*;
Class.forName( "com.mysql.jdbc.Driver" );
String dburl = "jdbc:mysql://localhost/dbName";
Connection con = DriverManager.getConnection ( dburl, ID, PWD );
public static Connection getConnection() throws Exception{
String url = "jdbc:oracle:thin:@117.16.46.111:1521:xe";
String user = "smu";
String password = "smu";
Connection conn = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
return conn;
}
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select no from user" );
stmt.execute(โqueryโ); //any SQL
stmt.executeQuery(โqueryโ); //SELECT
stmt.executeUpdate(โqueryโ); //INSERT, UPDATE, DELETE
ResultSet rs = stmt.executeQuery( "select no from user" );
while (rs.next())
System.out.println(rs.getInt( "no"));
rs.close();
stmt.close();
con.close();
// GET
public List<GuestBookVO> getGuestBookList(){
List<GuestBookVO> list = new ArrayList<>();
GuestBookVO vo = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select * from guestbook";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
vo = new GuestBookVO();
vo.setNo(rs.getInt(1));
vo.setId(rs.getString(2));
vo.setTitle(rs.getString(3));
vo.setConetnt(rs.getString(4));
vo.setRegDate(rs.getString(5));
list.add(vo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, rs);
}
return list;
}
// ADD
public int addGuestBook(GuestBookVO vo){
int result = 0;
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtil.getConnection();
String sql = "insert into guestbook values("
+ "guestbook_seq.nextval,?,?,?,sysdate)";
ps = conn.prepareStatement(sql);
ps.setString(1, vo.getId());
ps.setString(2, vo.getTitle());
ps.setString(3, vo.getConetnt());
result = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(conn, ps);
}
return result;
}
// CLOSE
public static void close(Connection conn, PreparedStatement ps){
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
๐ Reference