「Java開発」JDBCドライバーによるoracleに接続するサンプルコード

Javaコード:
package com.startnews24.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class OrDbConn {
private static final String url ="jdbc:oracle:thin:@localhost:1521:orcl";
private static final String name ="ora_user";
private static final String passwd ="ora_pwd";
private static final String dbDriver_t ="oracle.jdbc.OracleDriver";
public Connection getConnection() {
Connection conn =null;
try{
Class.forName(dbDriver_t);
conn = DriverManager.getConnection(url, name, passwd);
if(conn !=null) {
System.out.println(“Oracelデータベースに接続成功");
}
}catch(ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void close(Connection conn) {
try{
if(conn !=null) {
if(!conn.isClosed()) {
conn.close();
}
}
}catch(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
OrDbConn conn=new OrDbConn();
Connection con = conn.getConnection();
try{
PreparedStatement ctnpt = con.prepareStatement(“select notename from cftnotetbl where noteid=1");
ResultSet rs = ctnpt.executeQuery();
if(rs.next())
System.out.println(rs.getString(1));
}catch(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.close(con);
}
}

Java

Posted by arkgame