学习oracle近一周了,做了一个jdbc连接oracle数据库的例子。可以实现增删改查的功能。很通用,复制过去改改url和数据库名和密码就可以运行,适合初学者学习。
import java.sql.*;
public class connect {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// String url="jdbc:oracle:oci:@orcl";
// //String url="jdbc:oracle:thin:@192.168.4.12:8080:orcl";
// String user="scott";
// String password="tiger";
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
String user = "user01";
String password = "u01";
// 插入数据
//String str = "insert into emp_xxx values(2001,'宁丽娟','Manager', 10000,2000,'12-7月-10',1005,10)";
//删除数据
// String str="delete from emp_xxx where ename='宁丽娟'";
//更新数据
String str="update emp_xxx set ename='宁娟娟'where deptno=10";
con = java.sql.DriverManager.getConnection(url, user, password);
// 创建状态
stmt = con.createStatement();
// 执行SQL语句,返回结果集
int k=stmt.executeUpdate(str);
// int j =
// stmt.executeUpdate("update emp set ENAME='jack' where EMPNO=7369");
// int k = stmt.executeUpdate("delete from emp where EMPNO=7900");
// t=stmt.executeUpdate("delete from emp_xxx where ename='宁丽娟'");
rs = stmt.executeQuery("SELECT ename,empno FROM emp_xxx");
// 对结果集进行处理
System.out.println(k);
while (rs.next()) {
int id = rs.getInt("EMPNO");
String name = rs.getString("ENAME");
// Integer age = rs.getObject("age") == null ? null :
// rs.getInt("age");
System.out.println(id + ": " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
// 释放资源
finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}