Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在一条语句中用java执行多个查询_Java_Mysql_Sql_Jdbc - Fatal编程技术网

在一条语句中用java执行多个查询

在一条语句中用java执行多个查询,java,mysql,sql,jdbc,Java,Mysql,Sql,Jdbc,您好,我想知道是否可以使用JDBC执行类似的操作,因为它目前提供了一个异常,即使在MySQL查询浏览器中也是可以的 "SELECT FROM * TABLE;INSERT INTO TABLE;" 虽然我确实意识到,拆分SQL查询字符串并执行两次语句是可能的,但我想知道是否有一种一次性的方法可以实现这一点 String url = "jdbc:mysql://localhost:3306/"; String dbName = "databaseinjection"; S

您好,我想知道是否可以使用JDBC执行类似的操作,因为它目前提供了一个异常,即使在MySQL查询浏览器中也是可以的

"SELECT FROM * TABLE;INSERT INTO TABLE;"
虽然我确实意识到,拆分SQL查询字符串并执行两次语句是可能的,但我想知道是否有一种一次性的方法可以实现这一点

    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "databaseinjection";
    String driver = "com.mysql.jdbc.Driver";
    String sqlUsername = "root"; 
    String sqlPassword = "abc";

    Class.forName(driver).newInstance();

    connection = DriverManager.getConnection(url+dbName, sqlUsername, sqlPassword);

为什么不尝试为此编写一个
存储过程

您可以将
结果集
取出,并在相同的
存储过程中
您可以
插入
所需内容


唯一的问题是,如果在
选择之后
插入
,您可能无法在
结果集中获得新插入的行
,您可以使用批更新,但查询必须是操作(即插入、更新和删除)查询

我想知道是否可以使用JDBC执行类似的操作

是的,这是可能的。据我所知,有两种方法。是的

  • 通过将数据库连接属性设置为允许多个查询, 默认情况下由分号分隔
  • 通过调用返回游标隐式的存储过程
  • 以下示例演示了上述两种可能性

    示例1:(允许多个查询):

    发送连接请求时,需要将连接属性
    allowMultiQueries=true
    附加到数据库url。这是那些已经存在的连接属性的附加属性,例如
    autoReConnect=true
    ,等等。。
    allowMultiQueries
    属性的可接受值为
    true
    false
    yes
    no
    。任何其他值在运行时都会被拒绝,并出现
    SQLException

    String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";  
    
    除非传递这样的指令,否则将抛出
    SQLException

    您必须使用或其其他变体来获取查询执行的结果

    boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );
    
    要遍历和处理结果,需要执行以下步骤:

    READING_QUERY_RESULTS: // label  
        while ( hasMoreResultSets || stmt.getUpdateCount() != -1 ) {  
            if ( hasMoreResultSets ) {  
                Resultset rs = stmt.getResultSet();
                // handle your rs here
            } // if has rs
            else { // if ddl/dml/...
                int queryResult = stmt.getUpdateCount();  
                if ( queryResult == -1 ) { // no more queries processed  
                    break READING_QUERY_RESULTS;  
                } // no more queries processed  
                // handle success, failure, generated keys, etc here
            } // if ddl/dml/...
    
            // check to continue in the loop  
            hasMoreResultSets = stmt.getMoreResults();  
        } // while results
    
    示例2:遵循的步骤:

  • 使用一个或多个
    选择
    DML
    查询创建过程
  • 使用
    CallableStatement
    从java调用它
  • 您可以捕获过程中执行的多个
    结果集。
    无法捕获DML结果,但可以发出另一个
    select

    查找表中的行是如何受到影响的 样本表和程序:

    mysql>创建表tbl_mq(i int not null auto_increment,name varchar(10),主键(i));
    查询正常,0行受影响(0.16秒)
    mysql>分隔符//
    mysql>创建过程多_查询()
    ->开始
    ->从tbl_mq中选择count(*)作为名称_count;
    ->在tbl_mq(名称)中插入值('ravi');
    ->选择最后一个插入id();
    ->从tbl_mq中选择*;
    ->结束;
    -> //
    查询正常,0行受影响(0.02秒)
    mysql>分隔符;
    mysql>调用multi_query();
    +------------+
    |姓名/人数|
    +------------+
    |          0 |
    +------------+
    一行一组(0.00秒)
    +------------------+
    |最后插入id()|
    +------------------+
    |                3 |
    +------------------+
    一行一组(0.00秒)
    +---+------+
    |我的名字|
    +---+------+
    |1 |拉维|
    +---+------+
    一行一组(0.00秒)
    查询正常,0行受影响(0.00秒)
    
    来自Java的调用过程:


    根据我的测试,正确的标志是“allowMultiQueries=true”

    提示:如果您有多个连接属性,请使用以下命令将它们分开:

    &
    
    给你一些东西,比如:

    url="jdbc:mysql://localhost/glyndwr?autoReconnect=true&allowMultiQueries=true"
    
    我希望这能帮助一些人

    问候,


    Glyn

    我认为这是多选择/更新/插入/删除的最简单方法。在使用executeUpdate(str)(只需使用new int(count1,count2,…))选择之后,您可以运行任意数量的更新/插入/删除操作(您必须先进行选择(如果需要,可以使用一个虚拟操作)),如果您需要新的选择操作,请关闭“语句”和“连接”,并为下一次选择创建新选项。例如:

    String str1 = "select * from users";
    String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
    String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
    try{  
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);  
        theStatement = theConnection.prepareStatement(str1);
        ResultSet theResult = theStatement.executeQuery();
        int count8 = theStatement.executeUpdate(str9);
        theStatement.close();
        theConnection.close();
        theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
        theStatement = theConnection.prepareStatement(str2);
        theResult = theStatement.executeQuery();
    
        ArrayList<Port> portList = new ArrayList<Port>();
        while (theResult.next()) {
            Port port = new Port();
            port.setPort_id(theResult.getInt("port_id"));
    
            portList.add(port);
        }
    
    String str1=“选择*来自用户”;
    String str9=“将值(“+value1+”、“+value2+”、“+value3+”、“+value4+”)插入`端口'(设备id、位置、端口类型、数据点)中”;
    String str2=“从端口中选择端口id,其中设备id='“+value1+”,位置='“+value2+”,端口类型='“+value3+”;
    试试{
    Class.forName(“com.mysql.jdbc.Driver”).newInstance();
    连接=(连接)驱动程序管理器.getConnection(dbURL、dbuser、dbpassword);
    声明=连接准备声明(str1);
    结果集theResult=statement.executeQuery();
    int count8=statement.executeUpdate(str9);
    语句。关闭();
    connection.close();
    connection=DriverManager.getConnection(dbURL、dbuser、dbpassword);
    声明=连接准备声明(str2);
    结果=statement.executeQuery();
    ArrayList端口列表=新的ArrayList();
    while(theResult.next()){
    端口=新端口();
    port.setPort_id(结果getInt(“port_id”);
    portList.add(端口);
    }
    

    我希望它有助于

    在存储过程中调用存储过程。这意味着您在想要进行更改时也不必重新部署代码。您必须在连接字符串
    allowMultiQueries=true
    中设置一个属性。可能重复:如何在java中执行复合sql查询?[1][1]:嗨,Rahul,对于这个项目,我使用的是一个普通的旧连接对象,您知道我应该在哪里设置“allowMultiQueries=true”。在问题中添加了连接对象代码。不幸的是,Derby的嵌入式版本无法使用此方法。@user2428118:原因?观察到任何错误?您是否检查了驱动程序是否支持此功能?我添加了allowMultiQueries=true,工作正常:)谢谢@RavinderReddyYou不能将此方法用于“调用存储过程名称('abc',984)”查询?打开数据库连接的成本非常高。这不是一个好的做法
    &amp;
    
    url="jdbc:mysql://localhost/glyndwr?autoReconnect=true&amp;allowMultiQueries=true"
    
    String str1 = "select * from users";
    String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
    String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
    try{  
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);  
        theStatement = theConnection.prepareStatement(str1);
        ResultSet theResult = theStatement.executeQuery();
        int count8 = theStatement.executeUpdate(str9);
        theStatement.close();
        theConnection.close();
        theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
        theStatement = theConnection.prepareStatement(str2);
        theResult = theStatement.executeQuery();
    
        ArrayList<Port> portList = new ArrayList<Port>();
        while (theResult.next()) {
            Port port = new Port();
            port.setPort_id(theResult.getInt("port_id"));
    
            portList.add(port);
        }