import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo {
private static final String URL = “jdbc:oracle:thin:@localhost:1521:ORCL” ;
private static final String USERNAME = “scott” ;
private static final String PWD = “tiger” ;
public static void update() {//增删改
Statement stmt =null;
Connection connection = null;
try {
// a.导入驱动,加载具体的驱动类
Class.forName(“oracle.jdbc.OracleDriver”);//加载具体的驱动类
// b.与数据库建立连接
connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
// c.发送sql,执行(增删改)
stmt = connection.createStatement() ;
//增加为下面的语句:
String sql = “insert into mytab values(1,‘ls’)”;
//执行SQL
int count = stmt.executeUpdate(sql);//返回值表示增删改 几条数据
//d.处理结果
if(count>0) {
System.out.println(“操作成功!”);
}
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally {
try {
if(stmt!=null)stmt.close();
if(connection!=null)connection.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
//查找
public static void query() {
Statement stmt =null;
Connection connection = null;
ResultSet rs = null;
try {
// a.导入驱动,加载具体的驱动类
Class.forName(“oracle.jdbc.OracleDriver”);//加载具体的驱动类
// b.与数据库建立连接
connection = DriverManager.getConnection(URL,USERNAME,PWD) ;
// c.发送sql,执行查
stmt = connection.createStatement() ;
//模糊查询名字有x 的信息
String name = “x”;
String sql=“select *from mytab where name like '%”+name+"%’";
//执行SQL(增删改是executeUpdate(),查询executeQuery())
rs = stmt.executeQuery(sql);//默认指向第0行 next():1:下移,2判断下移之后的元素是否为空 如果有数据true 为空false
//rs.getXxx(); 获取rs指向行的数据 eg:getInt() getString() getDate()
//d.处理结果
while(rs.next()) {
//下面的两行语句可以用 序列号替代
/int sno = rs.getInt(“id”);
String sname = rs.getString(“name”);/ //开发推荐写第一个 因为下面的比较乱
int sno = rs.getInt(1);//下标:从1开始计数
String sname = rs.getString(2);
System.out.println(sno+"----"+sname);
}
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally {
try {
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
if(connection!=null)connection.close();//顺序;先打开的 后关 就像堆栈一样
}catch(SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
update();
//query();
}
}




