Computer/JAVA

JDBC 데이터베이스 연결

미처서 2014. 8. 8. 14:47

DBUtil.java

public class DButil {


public static Connection getConnection() {

Connection conn = null;

Properties p = new Properties();


try {

p.load(new FileReader(

"src/com/ninethirty/hellolecture/nfc/dbinfo.properties"));

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

String driver = p.getProperty("driver");

try {

Class.forName(driver);

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

try {

conn = DriverManager.getConnection(p.getProperty("url"),

p.getProperty("userid"), p.getProperty("password"));


System.out.println("DB Connection");

} catch (SQLException e) {

e.printStackTrace();

}


return conn;

}


public static void close(Connection conn, Statement st) {

try {

if (conn != null)

conn.close();

if (st != null)

st.close();


} catch (SQLException e) {

e.printStackTrace();

}

}


}




dbinfo.properties

driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
userid=hr
password=hr




사용하기
try {
conn = DBUtil.getConnection();
st = conn.createStatement();
String users_sql = "select * from tablename";
rs = st.executeQuery(users_sql);
while (rs.next()) {
user_id = rs.getString(1);
user_name = rs.getString(2);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null)
rs.close();
}