Connecting to the database using jdbc. I would like to create a variable in the SQL query, which could then be substituted into the main logic of the Java program. How can this be implemented?

Closed due to the fact that the essence of the issue is incomprehensible by the participants of the Senior Pomidor , user207618, br3t , Lex Hobbit , rjhdby 11 Aug '17 at 20:59 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • I would like to create a variable in the SQL query, which could then be substituted into the main logic of the Java program. If you mean that executing a SQL query on a MySQL server should create a variable on a client workstation that is available in your Java program — this is impossible. And if something else is, then it would probably be a good idea to think through the wording of the question better ... - Akina

2 answers 2

Set up a connection like this:

Connection conn = DriverManager.getConnection("url", "username", "password"); 

And then write down your data in the table:

 // Вам понадобится сам sql запрос String sql = "INSERT INTO exemple (id, val) VALUES (DEFAULT, (?))" //Создаете PreparedStatement что-бы не забыть закрыть лучше открывать в try-with-resources try (final PreparedStatement statement = //сюда передаете sql запрос: connection.prepareStatement(sql)) { //Тут у вас задаются значения для (?). //Вместо (?) подставляете значение ("test"). Индексация параметров(wildcard) - (?) начинается от 1. statement.setString(1, "test"); //Выполняете сам запрос в базу. statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } 

This will work if your table looks like this:

 CREATE TABLE exemple ( id SERIAL, val TEXT, ); 

    You need to use PreparedStatement . Here is an example from JavaDoc

     PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setBigDecimal(1, 153833.00) pstmt.setInt(2, 110592)