执行SQL语句的方式

JDBC不仅可执行查询,也可以执行DDL,DML等SQL语句,从而允许通过JDBC最大限度地控制数据库。

使用executeUpdate或者使用executeLargeUpdate方法来执行DDL和DML语句:

 编写程序,通过executeUpdate方法在mysql当前数据库下创建一个数据库表 示范:

public class JDBC {
    String driver;
    String url;
    String user;
    String password;
    
    //查询该数据库是否有对应的表,有则返回ture,没有返回false
    public boolean tableIsExists(String tableName){
        try{
            Connection conn =DriverManager.getConnection(url,user,password);
            Statement statement =conn.createStatement();
            String sql = "select table_name from information_schema.tables where table_schema='test'";
            ResultSet resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                String queryTableName = resultSet.getString(1);
                System.out.println(queryTableName);
                if(queryTableName.equals("tb_test")){
                    return true;
                }
            }
        }catch(Exception e){}
        return false;
    }
    
    public void createTableJDBC(String tableName){
        try{
            Connection conn =DriverManager.getConnection(url,user,password);
            Statement statement =conn.createStatement();
            if(!tableIsExists(tableName)){
                System.out.println("当前数据库没有"+tableName+"表格,将创建"+tableName+"数据库表");
                String sql = "create table "+tableName+"("
                        + "test_id int auto_increment primary key,"
                        + "test_name varchar(255),"
                        + "test_desc text)";
                int result = statement.executeUpdate(sql);
            }else{
                System.out.println("当前数据库有"+tableName+"表格,不创建"+tableName+"数据库表");
            }
            
        }catch(Exception e){}
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JDBC jdbc = new JDBC();
        
        jdbc.initParam("mysql.properties");
        jdbc.createTableJDBC("tb_test");
    }
}

 第一次运行结果如下:

tb_adminuser
tb_user
当前数据库没有tb_test表格,将创建tb_test数据库表

 第二此运行结果如下(假如没有操作mysql数据的话):

tb_adminuser
tb_test
当前数据库有tb_test表格,不创建tb_test数据库表

 编写程序,对上述新增表添加数据:

public class JDBC {
    String driver;
    String url;
    String user;
    String password;
    public void initParam(String paramFile){
        try{
            Properties props = new Properties();
            props.load(new FileInputStream(paramFile));
            driver = props.getProperty("driver");
            url = props.getProperty("Url");
            user = props.getProperty("user");
            password = props.getProperty("password");
            
        }catch(Exception e){}
    }
    
    public void addData(String table,String sql){
        try{
            Connection conn =DriverManager.getConnection(url,user,password);
            Statement statement =conn.createStatement();
            int resultRow = statement.executeUpdate(sql);
            System.out.println("对"+table+"表添加了1条数据,该表受影响行数为"+resultRow);
        }catch(Exception e){}
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JDBC jdbc = new JDBC();

        jdbc.initParam("mysql.properties");
        String table = "tb_test";
        String sql = "insert into "+table+"(test_name,test_desc) values('hjl','0');";
        jdbc.addData(table, sql);
    }
}

 运行的效果为:

对tb_test表添加了1条数据,该表受影响行数为1

 通过两个代码进行测试可以得知,使用executeUpdate(String sql) 是可以对数据库进行DML语句与DDL语句操作的,不同的是,DDL语句因为不是对表中内容进行操作,因此返回的值为0;而DML语句是对表格内容进行操作的,因此返回影响表格内容的行数。

使用execute方法执行SQL语句:

 Statement的execute()方法几乎可以执行任何SQL语句,但它执行SQL语句时比较麻烦,通常都是使用executeQuery()方法或者executeUpdate()方法来执行SQL语句;只有不清楚SQL语句的类型,为了保证不出错,最好是用execute()方法来执行该SQL语句。

 使用execute()的返回值是boolean,那么如何来获取执行查询语句获得的ResultSet对象,以及如何获取执行DDL或者DML语句获得的int数值呢?针对这种情况,Statement提供了如下两个方法:

  1.getResultSet(): 该方法返回Statement执行查询语句所返回的ResultSet对象。

  2. getUpdateCount():该方法返回statementDDL,DML语句所影响的记录行数。

 下面程序示范了使用Statment的execute()方法来执行任意的SQL语句。

public class JDBC {
    
    //使用execute方法进行对表查询
    public void queryByExecuteMethod(String table){
        try{
            String sql = "select * from "+table;
            boolean b = statement.execute(sql);
            if(b){
                System.out.println("execute方法返回"+b);
                ResultSet result = statement.getResultSet();
                int count = 0;
                while(result.next()){
                    count++;
                }
                System.out.println("一共查询了"+count+"条记录");
            }else{System.out.println("execute方法返回"+b);}
        }catch(Exception e){}
    }
    
    //使用execute方法进行DML删除该表的内容
    public void deleteDataByExecuteMethod(String table){
        try{
            String sql = "delete from "+table;
            boolean b = statement.execute(sql);
            if(!b){
                System.out.println("execute方法返回"+b);
                System.out.println(table+"受影响行数为:"+statement.getUpdateCount());
            }else{System.out.println("execute方法返回"+b);}
        }catch(Exception e){}
    }
    
    //使用execute方法进行DDL删除该表
    public void dropTableByExecuteMethod(String table){
        try{
            String sql = "drop table "+table;
            boolean b = statement.execute(sql);
            if(!b){
                System.out.println("execute方法返回"+b);
                System.out.println(table+"受影响行数为:"+statement.getUpdateCount());
            }else{System.out.println("execute方法返回"+b);}
        }catch(Exception e){}
    }
    
    Connection conn = null;
    Statement statement = null;
    public JDBC(String paramFile){
        try{
            Properties props = new Properties();
            props.load(new FileInputStream(paramFile));
            String driver = props.getProperty("driver");
            String url = props.getProperty("Url");
            String user = props.getProperty("user");
            String password = props.getProperty("password");
            conn =DriverManager.getConnection(url,user,password);
            statement =conn.createStatement();
            
        }catch(Exception e){}
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String table = "tb_test";
        JDBC jdbc_2 = new JDBC("mysql.properties");
        jdbc_2.queryByExecuteMethod(table);
        jdbc_2.deleteDataByExecuteMethod(table);
        jdbc_2.dropTableByExecuteMethod(table);
    }
}

 上述程序中,使用了execute()方法执行了三种SQL语句,分别是查询语句,DML语句与DDL语句,其中查询语句返回的是True值,根据true值从Statement对象中获取ResultSet对象,而根据false值,从Statement对象中获取getUpdateCount()方法的值,其运行效果为:

execute方法返回true
一共查询了2条记录
execute方法返回false
tb_test受影响行数为:2
execute方法返回false
tb_test受影响行数为:0

猜你喜欢

转载自www.cnblogs.com/hjlin/p/11440060.html