import java.sql.*;
//jdbc访问oracle
public class JavaOra {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","m123");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from emp");
while(rs.next()) //返回第二个字段(rs.getString(2))即ename的值。
System.out.println("用户名:"+rs.getString(2));
st.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
import java.sql.*;
public class TestShiWu {
public static void main(String[] args) {
Connection conn=null;
try{
//加载oracle的jdbc驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(java.lang.ClassNotFoundException e){
System.err.print("ClassNotFoundException");
System.err.println(e.getMessage());
}
try{
//连接到数据库,orcl是数据库名,scott是用户,m123是密码
conn=DriverManager.getConnection("jdbc:oracle:oci8:@orcl","scott","m123");
//声明statement对象
//加入事务处理
conn.setAutoCommit(false); //设置不自动提交
Statement stmt=conn.createStatement();
//执行sql语句
stmt.executeQuery("update emp set sal=sal-100 where ename='SCOTT'");
int i=7/0;
stmt.executeQuery("update emp set sal=sal+100 where ename='SMITH'");
conn.commit(); //提交事务
//遍历结果集并将每条记录的ename列打印出来
/* while(re.next()){
System.out.println("雇员名:"+re.getString(1));
}*/
//关闭stmt和conn
stmt.close();
conn.close();
}catch(SQLException ex){
try{
conn.rollback(); //若发生异常时,进行回滚,事务操作不会生效。
}catch(SQLException ex1){
ex1.printStackTrace();
}
System.err.print("SQLException:"+ex.getMessage());
}
}
}