当前位置:Gxlcms > 数据库问题 > JDBC1

JDBC1

时间:2021-07-01 10:21:17 帮助过:4人阅读

class TestInsert { public static void main(String[] args){ //声明jdbc变量 Connection conn=null; Statement stmt=null; //声明JDBC参数 String driver="oracle.jdbc.driver.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:orcl"; String username="scott"; String password="oracle"; //1 加载驱动类 try { Class.forName(driver); //2 获取数据库连接对象(连接指定的数据库) conn=DriverManager.getConnection(url,username,password); //3 获取sql命令对象(编译和发送sql命令给数据库) stmt=conn.createStatement(); //4 创建sql命令 String sql="insert into dept values(1,‘清华‘,‘北京‘)"; //5 指定sql命令 int i=stmt.executeUpdate(sql); System.out.println("执行结果:"+i); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //6 关闭资源 try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

2、JDBC-修改(与JDBC-新增对比:除sql语句不同外,其他一致)

public class TestUpdate {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //2创建连接对象
        Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott","oracle");
        //3创建sql命令对象
        Statement stmt=conn.createStatement();
        //4创建sql命令
        String sname="张三";
        String sql="update student set sname=‘"+sname+"‘ where snum=2";
        //5执行sql命令
        int i=stmt.executeUpdate(sql);
        System.out.println(i);
        //6关闭资源
        stmt.close();
        conn.close();
        
    }
}

3、JDBC-删除(与JDBC-新增对比:除sql语句不同外,其他一致)

public class TestDel {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1 加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
        //2创建连接对象
            Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@LocalHost:1521:orcl", "scott", "oracle");
        //3创建sql命令对象
            Statement stmt=conn.createStatement();
        //4创建sql命令
            String sql="delete from student where snum=2";
        //5执行sql命令
            int i=stmt.executeUpdate(sql);
            System.out.println("删除数据量:"+i);
        //6关闭资源
            stmt.close();
            conn.close();
    }
}

JDBC1

标签:scott   nts   获取   rate   oid   jdb   connect   for   java   

人气教程排行