Kamil Kamil - 3 months ago 11
SQL Question

JAVA update Database - wrong

package application;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class Query {

private static final String DRIVER_CLASSNAME = "org.sqlite.JDBC";
private static final String PASSWORD = "";
private static final String USERNAME = "";

protected static String base = "data/pezalDB";
private static String JDBC_URL = "jdbc:sqlite:" + base + ".db";

protected static Connection connection;
protected static Statement statement;
public static ResultSet resultSet;

public static void connectToDatabase() throws ClassNotFoundException, SQLException {
Class.forName(DRIVER_CLASSNAME);
connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
}

public static void executeSql(String sql) throws SQLException {

statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
}

public static void close() throws SQLException {
resultSet.close();
statement.close();
connection.close();
}

}

public class TableDB {

private int id;
private String namePL;
private String nameEN;

public TableDB(String namePL, String nameEN) {
this.namePL = namePL;
this.nameEN = nameEN;
}
}

public class QueryMethods extends Query {

static String table = "dictionary";
static String sql;

public static void addValue() {
try {
connectToDatabase();

sql = "UPDATE dictionary SET namePL = 'QWE' WHERE id = 2";

executeSql(sql);
close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

addValue();

}
}


I have a problem :

java.sql.SQLException: query does not return ResultSet
at org.sqlite.jdbc3.JDBC3Statement.executeQuery(JDBC3Statement.java:85)
at application.QueryMethods.addValue(QueryMethods.java:18)
at application.TestQuery.main(TestQuery.java:10)


What is wrong? When I read from database all is ok but more function is wrong.

Did not work Update and Insert
.................................................................................................................................................................................................................................................

Answer

You are trying to execute a SQL UPDATE statement with the executeQuery() method. executeQuery() cannot take statements that update the database, such as UPDATE, INSERT or DELETE. Replace this line with:

int rowsUpdated = statement.executeUpdate(sql);