Six steps of JDBC programming:
import the ojdbc file in the preparation work, then right-click to select the add path
build path--> add oracle's ojdbc.jar package to the oracle installation directory
(1). Register the driver
Class.forName("oracle.jdbc .OracleDriver");
(2).Connect to the database
String url = "jdbc:oracle:thin:@localhost:1521:xe";//Where xe is sid
String user = "XXX";
String password = "XXX";
Connection conn = DriverManager.getConnection(url,name,password);
(3).Create a porter statement
Statement state = conn.createStatement();
(4).Move data, execute SQL statement
String sql = "select id,name from s_emp "; //"insert into s_emp(id,name) values(12,'zhangsan')";
ResultSet rs = state.executeQuery(sql);
(5). Processing the result set
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString(2);
System.out.println(id+" "+name);
}
(6).关闭连接
rs.close();
state.close();
conn.close();
The code as shown below implements the insert operation
- publicvoid test_insert()
- {
- String driver="oracle.jdbc.driver.OracleDriver";
- String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";//orcl为sid
- String user="briup";
- String password="briup";
- Connection conn=;
- Statement stat=;
- try {
- //1, register the driver
- Class.forName(driver);
- //2, get the connection
- conn= DriverManager.getConnection(url, user, password);
- //System.out.println(conn);
- //3, create a statement object
- stat=conn.createStatement();
- //4, execute the sql statement
- String sql="insert into lover values(5,'suxingxing',to_date('21-9-2016','dd-mm-yyyy'))";
- stat.execute(sql);
- //System.out.println(stat.execute(sql));
- //5. Process the result set, if there is one, process it, if not, do not need to process it. Of course, the insert statement does not need to be processed.
- } catch (Exception e) {
- e.printStackTrace ();
- }
- finally{
- //6, close the resource
- try {
- if(stat!=)stat.close();
- } catch (SQLException e) {
- e.printStackTrace ();
- }
- try {
- if(conn!=)conn.close();
- } catch (SQLException e) {
- e.printStackTrace ();
- }
- }
- }