source

실행으로 데이터 조작 문을 발행할 수 없습니다.쿼리()

goodcode 2022. 11. 25. 21:26
반응형

실행으로 데이터 조작 문을 발행할 수 없습니다.쿼리()

MySQL에는 2개의 테이블이 있습니다.tableA그리고.tableB. 다음 두 가지 쿼리를 실행하려고 합니다.

executeQuery(query1) 
executeQuery(query2)

다만, 다음의 에러가 표시됩니다.

can not issue data manipulation statements with executeQuery().

이것은 무엇을 의미합니까?

보다 실제로 필요한 데이터를 조작하기 위해서입니다.

여기 이 발췌문이 있습니다.executeUpdate()javadoc은 이미 자체 답변입니다.

지정된 SQL 문(INSERT, UPDATE 또는 DELETE 문 또는 SQL DDL 문 등 아무것도 반환하지 않는 SQL 문)을 실행합니다.

DML 스테이트먼트를 실행할 때는,executeUpdate/execute보다는executeQuery.

다음은 간단한 비교입니다.

executeQueryVSexecuteUpdateVSexecute

스프링 부트를 사용하는 경우 @Modifying 주석을 추가합니다.

@Modifying
@Query
(value = "UPDATE user SET middleName = 'Mudd' WHERE id = 1", nativeQuery = true)
void updateMiddleName();

삭제 쿼리의 경우 - 사용@Modifying그리고.@Transactional이 되기 전에@Query예를 들면:-

@Repository
public interface CopyRepository extends JpaRepository<Copy, Integer> {

    @Modifying
    @Transactional
    @Query(value = "DELETE FROM tbl_copy where trade_id = ?1 ; ", nativeQuery = true)
    void deleteCopyByTradeId(Integer id);

}

그런다고 해서java.sql.SQLException: Can not issue data manipulation statements with executeQuery()에러입니다.

편집:

이 답변은 많은 표가 올라가고 있기 때문에, 자세한 것은 문서도 참조해 주세요.

@트랜잭션

By default, CRUD methods on repository instances are transactional. For read operations, 
the transaction configuration readOnly flag is set to true. 
All others are configured with a plain @Transactional so that default transaction 
configuration applies.

@변경 중

Indicates a query method should be considered as modifying query as that changes the way 
it needs to be executed. This annotation is only considered if used on query methods defined 
through a Query annotation). It's not applied on custom implementation methods or queries 
derived from the method name as they already have control over the underlying data access 
APIs or specify if they are modifying by their name.

Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL 
statements.

사용하다executeUpdate()data 조작 스테이트먼트를 발행합니다. executeQuery()는 SELECT 쿼리(즉, 결과 세트를 반환하는 쿼리)에만 사용됩니다.

그렇구나executeUpdate를 위한 것입니다.

다음은 차이점에 대한 간단한 요약입니다.http://www.coderanch.com/t/301594/JDBC/java/Difference-between-execute-executeQuery-executeUpdate

이 코드는, INSERT 에 값을 설정하고, SELECT 에 이 값의 LAST_INSERT_ID() 를 취득합니다.Java NetBeans 8.1, MySql 및 java 를 사용합니다.JDBC.드라이버

                try {

        String Query = "INSERT INTO `stock`(`stock`, `min_stock`,   
                `id_stock`) VALUES ("

                + "\"" + p.get_Stock().getStock() + "\", "
                + "\"" + p.get_Stock().getStockMinimo() + "\","
                + "" + "null" + ")";

        Statement st = miConexion.createStatement();
        st.executeUpdate(Query);

        java.sql.ResultSet rs;
        rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");                
        rs.next(); //para posicionar el puntero en la primer fila
        ultimo_id = rs.getInt("LAST_INSERT_ID()");
        } catch (SqlException ex) { ex.printTrace;}
@Modifying
@Transactional
@Query(value = "delete from cart_item where cart_cart_id=:cart", nativeQuery = true)
public void deleteByCart(@Param("cart") int cart); 

@query 앞에 @Modifying과 @Transnational을 추가하는 것을 잊지 마십시오.나한테는 효과가 있어

JPA에서 네이티브 쿼리를 사용하여 특정 조건으로 레코드를 삭제하려면 위에서 언급한 주석이 중요합니다.

executeQuery()a를 반환하다ResultSetJava/MySQL에 대해서는 잘 모르지만 인덱스를 작성하기 위해 필요한 것 같습니다.executeUpdate().

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_swing_db", "root", "root");

Statement smt = conn.createStatement();

String sql = "SELECT * FROM `users` WHERE `email` = " + email + " AND `password` = " + password + " LIMIT 1;";

String registerSql = "INSERT INTO `users`(`email`, `password`, `name`) VALUES ('" + email + "','" + password + "','" + name + "')";

System.out.println("SQL: " + registerSql);
            
int result = smt.executeUpdate(registerSql);
System.out.println("Result: " + result);

if (result == 0) {
   JOptionPane.showMessageDialog(this, "This is alredy exist");
} else {
  JOptionPane.showMessageDialog(this, "Welcome, Your account is sucessfully created");
  App.isLogin = true;
  this.dispose();
  new HomeFrame().show();
}
conn.close();

괄호 위에 executeUpdate() 외에 SQL 문을 사용하려면 변수를 추가해야 합니다.

예를 들어 다음과 같습니다.

PreparedStatement pst =  connection.prepareStatement(sql);
int numRowsChanged = pst.executeUpdate(sql);

언급URL : https://stackoverflow.com/questions/1905607/cannot-issue-data-manipulation-statements-with-executequery

반응형