V
V
Vadim Pirx2016-07-19 16:23:37
MySQL
Vadim Pirx, 2016-07-19 16:23:37

How to correctly pass such a request through jdbc?

public static void main(String[] args) throws SQLException, ClassNotFoundException {
          Connection conn = null;
          Statement  stmt = null;
          
          try {
              Class.forName(JDBC_DRIVER);
              System.out.println("Connecting to database...");
              conn = DriverManager.getConnection(DB_URL, USER, PASS);
              
              String sql="SET @mon=6; "
              		+ "SET @var1=(SELECT counter FROM electro.data_counter WHERE YEAR(date)= 2016 AND MONTH(date) = @mon-1); "
              		+ "SET @var2=(SELECT counter FROM electro.data_counter WHERE YEAR(date)= 2016 AND MONTH(date) = @mon); "
              		+ "SELECT @[email protected] AS Diff;";
              stmt = conn.createStatement();
              stmt.executeUpdate(sql);
//ResultSet rs = stmt.executeQuery(sql);

throws an exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax;
checked in workbench, the request works.
from the console works too:
mysql> SET @mon=6;
Query OK, 0 rows affected (0.00 sec)
mysql> SET @var1=(SELECT counter FROM ele
6 AND MONTH(date) = @mon-1);
Query OK, 0 rows affected (3.41 sec)
mysql> SET @var2=(SELECT counter FROM ele
6 AND MONTH(date) = @mon);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @[email protected] AS Diff;
+------+
| diff |
+------+
| 184 |
+------+
1 row in set (0.00 sec)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vamp, 2016-07-19
@pirxon

You have 4 different queries in the sql variable at once. You need to execute each request with a separate executeUpdate() call. Workbench itself determines the number of requests passed to it, separates them and executes them sequentially, one after another. And in the console, you entered each command separately, so you have no problems with the workbench and the console client.

V
Vadim Pirx, 2016-07-19
@pirxon

did not help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question