In MySQL I have two tables, tableA and tableB. I am trying to execute two queries:
executeQuery(query1)
executeQuery(query2)
But I get the following error:
can not issue data manipulation statements with executeQuery().
What does this mean?
To manipulate data you actually need executeUpdate() rather than executeQuery().
Here's an extract from the executeUpdate() javadoc which is already an answer at its own:
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
When executing DML statement , you should use executeUpdate/execute rather than executeQuery.
Here is a brief comparison :
If you're using spring boot, just add an #Modifying annotation.
#Modifying
#Query
(value = "UPDATE user SET middleName = 'Mudd' WHERE id = 1", nativeQuery = true)
void updateMiddleName();
For Delete query - Use #Modifying and #Transactional before the #Query like:-
#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);
}
It won't give the java.sql.SQLException: Can not issue data manipulation statements with executeQuery() error.
Edit:
Since this answer is getting many upvotes, I shall refer you to the documentation as well for more understanding.
#Transactional
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.
#Modifying
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.
Use executeUpdate() to issue data manipulation statements. executeQuery() is only meant for SELECT queries (i.e. queries that return a result set).
#Modifying
#Transactional
#Query(value = "delete from cart_item where cart_cart_id=:cart", nativeQuery = true)
public void deleteByCart(#Param("cart") int cart);
Do not forget to add #Modifying and #Transnational before #query. it works for me.
To delete the record with some condition using native query with JPA the above mentioned annotations are important.
That's what executeUpdate is for.
Here's a very brief summary of the difference: http://www.coderanch.com/t/301594/JDBC/java/Difference-between-execute-executeQuery-executeUpdate
This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver
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;}
executeQuery() returns a ResultSet. I'm not as familiar with Java/MySQL, but to create indexes you probably want a 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();
Besides executeUpdate() on the parentheses, you must also add a variable to use an SQL statement.
For example:
PreparedStatement pst = connection.prepareStatement(sql);
int numRowsChanged = pst.executeUpdate(sql);
I have two tables:
usuario (user in english): nombre, apellido, usuario, contrasena, id_perfil
perfil (profile in english): id_perfil, nombre
I have a login on my program using Java and MySQL and I want to know if the username and password entered by the user is correct, to send him to another Jframe.
I don't know much about SQL query but, I did my best here (I'm passing the username and password directly to the function):
public boolean login(String usuario, String contrasena) {
Dato_login d_lgn = new Dato_login();
boolean resultado = false;
sSQL = "SELECT u.nombre, u.apellido, u.usuario, u.contrasena, u.id_perfil, p.nombre AS perfil_nombre FROM "
+ "usuario U INNER JOIN perfil P u.id_perfil = p.id "
+ "WHERE u.usuario='" + usuario + "' AND u.contrasena='" + contrasena + "'";
// Java 7 try-with-resources
try (PreparedStatement pstm = con.prepareStatement(sSQL);
ResultSet rs = pstm.executeQuery(sSQL)) {
while (rs.next()) {
if (d_lgn.getContrasena().equals(contrasena)) {
resultado = true;
} else {
resultado = false;
}
d_lgn.setPerfil(rs.getString("perfil_nombre"));
d_lgn.setUsuario(rs.getString("usuario"));
d_lgn.setNombre(rs.getString("nombre"));
d_lgn.setApellido(rs.getString("apellido"));
d_lgn.setContrasena(rs.getString("contrasena"));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "SQLException:\n" + e, "Error: login(String usuario, String contrasena)", JOptionPane.ERROR_MESSAGE);
}
return resultado;
}
Is not working, it keeps telling me that there is not any user to log in.
What I need to change?
Also I would like to receive the name of the profile instead of the id of the user, I tried with INNER JOIN but I don't understand how it works correctly yet.
Table:
Error received:
Error in SQL Syntax
In this part:
sSQL = "SELECT u.nombre, u.apellido, u.usuario, u.contrasena, u.id_perfil FROM usuario U INNER JOIN perfil P ON p.nombre=u.nombre WHERE u.usuario='"
+ usuario + "' AND u.contrasena='" + contrasena + "'";
I don't see where a variables contrasena or usario is defined. Should that be ...AND u.usario='" + username + "' AND u.contrasena='" + password + "'"; instead? (putting aside a moment that this exposes a SQL Injection vulnerability). Also, it seems suspect that you're joining your usario and perfil tables on nombre. Is it the case that a User's name would be the same as their Profile name? Without understanding your domain and data model better, I can't really say.
If you also wanted to retrieve the profile name as well, your query could be this:
SELECT u.nombre, u.apellido, u.usuario, u.contrasena, p.nombre as perfil_nombre
FROM usario u
JOIN perfil p ON u.id_perfil = p.id_perfil
WHERE u.usuario = ? and u.contrasena = ?
Notice I'm joining usario and perfil on the id columns instead of nombre. I think you want the usario.perfil_id to match the perfil.id_perfil column.
Instead of con.createStatement() use con.createPreparedStatement(). See Using Prepared Statements for more information on that.
Lastly, to access the perfil.nombre from the ResultSet do this: rs.getString("perfil_nombre");
Also I am returning perfil.nombre instead of usario.nombre because you mentioned your want the profile name instead of the user name.
I am trying to execute an SQL Query to update some data in a Database column, but when I run the program I get the following error:
Hibernate: update DeputeAppeal set FilePath=/home/oleg/DeputeAppealsFiles/1 where id=38
[ERROR] [http-bio-8080-exec-2 09:21:21] (SqlExceptionHelper.java:logExceptions:131) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/home/oleg/DeputeAppealsFiles/1 where id=38' at line 1
This is the method in the DAO:
public void editFilePathName(DeputeAppeal deputeAppeal, String filePathName) {
Query query = sessionDao.getSession().createSQLQuery("update DeputeAppeal set FilePath=" + filePathName + " where id=" + deputeAppeal.getId());
query.executeUpdate();
}
You missed the single quotes for 'filePathName' in your query:
Query query = sessionDao.getSession().createSQLQuery("update DeputeAppeal set FilePath=" + filePathName + " where id=" + deputeAppeal.getId());
Use this instead :
Query query = sessionDao.getSession().createSQLQuery("update DeputeAppeal set FilePath = '" + filePathName + "' where id=" + deputeAppeal.getId());
I am trying to get bill details using following query
String hql = "from BillDetails as bd "
+ "left join fetch bd.billPaidDetails as bpd"
+ "where bd.client.id=:cid "
+ "and sum(bpd.amount)<bd.total "
+ "order by bd.addDate";
Query query = session.createQuery(hql);
query.setParameter("cid", cid);
obj = query.list();
Here one bill have many billPaidDetails I want to fetch only those bills that are not fully paid for that I am using sum(bpd.amount)<bd.total in where condition but this is showing
Exception org.hibernate.exception.GenericJDBCException: could not extract ResultSet
How to resolve above exception?
update to List<BillDetails> obj = query.list();.if it can not resolve your problem.I want you show us by the all exception and related entities.
I have a field this is mounted in run-time, like a join of another fields. Look:
public String getNumeroCip() {
if (this.getId() == null) {
return "BR0000000000000";
}
String idFormated = String.format("%011d", this.getId());
return "BR" + idFormated + this.produto.getProduto().getSufixo();
}
This is my field, mounted in run-time. I can call it doing: bean.numeroCip.
But if i try use this in a HQL, like this:
#NamedQuery(name = "Ar.findByNumeroArOrCip", query = "SELECT c FROM AR c "
+ "JOIN FETCH c.produto "
+ "JOIN FETCH c.situacao "
+ "WHERE c.numeroAr = :numeroAr OR c.numeroCip = :numeroCip")
I got the following error when i try start tomcat server:
Caused by: org.hibernate.HibernateException: Errors in named queries: Ar.findByNumeroArOrCip
Transient fields cannot be used in HQL queries. In the end HQL query is translated to the SQL query, which is then executed against database. Database is not aware of fields of Java objects.