JDBC编程的六个步骤:
准备工作中导入ojdbc文件,然后右键选中添加路径
build path-->到oracle安装目录里添加oracle的ojdbc.jar包
(1).注册驱动
Class.forName("oracle.jdbc.OracleDriver");
(2).连接数据库
String url = "jdbc:oracle:thin:@localhost:1521:xe";//其中xe为sid
String user = "XXX";
String password = "XXX";
Connection conn = DriverManager.getConnection(url,name,password);
(3).创建搬运工statement
Statement state = conn.createStatement();
(4).搬运数据,执行SQL语句
String sql = "select id,name from s_emp"; //"insert into s_emp(id,name) values(12,'zhangsan')";
ResultSet rs = state.executeQuery(sql);
(5).处理结果集
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();
如下面所示代码,实现插入操作
-
public void 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= null;
-
Statement stat= null;
-
try {
-
//1、注册驱动
-
Class.forName(driver);
-
//2、获取连接
-
conn= DriverManager.getConnection(url, user, password);
-
//System.out.println(conn);
-
//3、创建statement对象
-
stat=conn.createStatement();
-
//4、执行sql语句
-
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、处理结果集,如果有的话就处理,没有就不用处理,当然insert语句就不用处理了
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
finally{
-
//6、关闭资源
-
try {
-
if(stat!= null)stat.close();
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
try {
-
if(conn!= null)conn.close();
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
}
-
}