SQL query can't execute when it contains selected autoincrement row - java

I have in one java class a method which SELECT one column from a table from my database, and that column is an INT type in the database, and then I selected items from that column, put in a List<Long> and method returns this List. Here is the method:
public List<Long> vratiSveSifreRacuna() throws SQLException {
String sqlVratiSifruRacuna = "SELECT RacunID FROM racun";
Statement stat = konekcija.createStatement();
ResultSet rs = stat.executeQuery(sqlVratiSifruRacuna);
Long racunID = 0L;
List<Long> sifre = new ArrayList<>();
while (rs.next()){
//racunID = rs.getLong("RacunID");
sifre.add(new Long(rs.getInt("RacunID")));
}
return sifre;
}
The problem is, when I start debuging line by line, on this line:
ResultSet rs = stat.executeQuery(sqlVratiSifruRacuna);
it crashes, it jumps on exception. It cannot execute this query and I don't know why, because similar queries it execute well. Do you know what could be the problem? Is the problem maybe because the column I want to select is autoincrement and primary key? I don't know...

Your public (assuming static) method needs the connection object passed into it as an argument as it is not available in the local scope:
public static List<Long> vratiSveSifreRacuna(Connection konekcija) throws SQLException {
String sqlVratiSifruRacuna = "SELECT RacunID FROM racun";
Statement stat = konekcija.createStatement();
ResultSet rs = stat.executeQuery(sqlVratiSifruRacuna);
Otherwise include connection inside local context:
public static List<Long> vratiSveSifreRacuna(String url, String username, String password) throws SQLException {
Connection konekcija = DriverManager.getConnection(url, username, password);
String sqlVratiSifruRacuna = "SELECT RacunID FROM racun";
Statement stat = konekcija.createStatement();
ResultSet rs = stat.executeQuery(sqlVratiSifruRacuna);

I solved the problem finally so I wanted to share the solution. The problem was actually stupid, I accidentally put the code line which makes connection with database below the line where I called this method. So there where the method was called, sql query was actually empty, so it alerts error nullPointerException.

Related

rs.next() is returning false in while statement

So, I'm trying to extract msgID and msgStatus values from database for each reference Id(variable msgRefList) stored in the list object and I'm trying to store these extracted values in String objects for further processing. But rs.next() method is returning false and hence it is not going into the while loop where the assignment statements are. I checked in database with the query that i'm using in the code and it shows one record in the result, but still rs.next() is returning false. Screenshot attached with the database results.
Below is the actual code that i'm using
List<String> msgRefList = listofRefrnceValues:
try {
Connection connect = connectToDB(ENV);
for(String reference: msgRefList){
String query="select ID, MSG_STS from TABLE where INSTR_ID = ?";
PreparedStatement stmt = connect.prepareStatement(query);
stmt.setString(1,reference);
ResultSet rs = stmt.executeQuery();
if(rs!=null){
while(rs.next()) {
P_MID = rs.getString("P_MID");
P_MSG_STS = rs.getString("P_MSG_STS");
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
You have some typos in your SQL-Query-String in java. Instead of TABLE you probably meant MINF (your real table) also all of your properties don't have the prefix P_ and ID is probably MID. So change:
String query="select ID, MSG_STS from TABLE where INSTR_ID = ?";
To:
String query="select P_MID, P_MSG_STS from MINF where P_INSTR_ID = ?";
And you'll be fine.

retreive resultset from a custom query in java

my problem is not how to retreive data from resultset but it's about a resultset that it's not like we used to know
i will explain :
My database is on an remote server, connection via ssh established and everything works perfectly
but the problem is that i'm using resultset to get result from a "queryString" variable that i defined which get the query as a string from the front-end as a request and then , this query will be executed with the method i defined
and since we don't know beforehand from which table we re going to read data and how many columns are we going to retrieve , i didn't know how to make this method works on every recieve query
below is my code snippet :
#Override
public SqlQuery exeuteReceivedQuery(String queryString) throws SQLException {
ConnectToDataBase();
Statement st = (Statement) conn.createStatement();
ResultSet rs = st.executeQuery(queryString);
SqlQuery result = null;
while(rs.next()) {
result = new SqlQuery();
result.getQueryResult();
}
return result;
}
// controller
#GetMapping(value = "/{queryString}",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SqlQuery> getResults(#PathVariable("queryString") String queryString) throws SQLException {
SqlQuery cmd = sqlService.exeuteReceivedQuery(queryString);
return new ResponseEntity<>(cmd, HttpStatus.OK);
}
Does anyone of you have an idea on how to do this ?
Thanks in advance :)
You can access the ResultSet's metadata
rs.getMetaData().getColumnCount();
and then
rs.getMetaData().getColumnName(i);
You can obtain from the metadata columns, names, data types etc. all you need to extract the results

How do I get the variables in a column from java and sql?

So say a column is named Names I want to get a ArrayList of every variable inside of this column. Example:
Names
Test
Test1
Test3
River
World
Etc
I want to get all of that into an array list. Thanks for the help!
You're not giving much information in your question (e.g. what is the table you'd like to query), so here's a somewhat generic solution:
public List<String> retrieveAllColumnValues(Connection connection) throws SQLException {
String query = "SELECT Names FROM MyTable";
List<String> values = new ArrayList<>();
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
values.add(rs.getString("Names"));
}
rs.close();
}
return values;
}
Getting data from the database through JDBC roughly consist of the following parts:
You have a Connection which you use for creating SQL Statements
When you execute the Statement, you get a ResultSet, which contains the values returned by your query
You iterate through the ResultSet and do what you need to with the values

SELECT with WHERE using PreparedStatement

I have this method that selects movie showtimes by movie ID from a MySQL database and puts them in a Time[]. However, it is throwing a syntax exception near '? ORDER BY schedule_id' according to the trace.
public Time[] getShowTimes(int movieId) {
List<Time> list = new ArrayList<Time>();
try {
sql = "SELECT schedule_time FROM schedule WHERE movie_id = ? ORDER BY schedule_id";
ps = conn.prepareStatement(sql);
ps.setInt(1, movieId);
rs = ps.executeQuery(sql);
while(rs.next()) {
list.add(rs.getTime(1));
}
} catch(SQLException se) {
se.printStackTrace();
}
Time[] times = new Time[list.size()];
times = list.toArray(times);
return times;
}
I followed this example (if that helps). What could be wrong?
You are calling the executeQuery(String) method in your PreparedStatement, and that call is just inherited from Statement. But Statement just executes the query without any PreparedStatement placeholder semantics, hence the error.
Instead, you want to call the executeQuery() (no arguments) method. The SQL has already been prepared, and all placeholders have been assigned values, so the SQL argument string is not needed again.
rs = ps.executeQuery();

Oracle JDBC Driver ResultSet PreparedStatement Throws ORA-009900 invalid SQL statement Exception

I am using Oracle JDBC Driver ojdbc6.jar. When executing a PreparedStatement the ResultSet is returned. However when trying to get details back of what has been saved, I am unable to get this and it throws an Exception.
Below is the code:
public Processor {
private Connection connection;
public Processor() throws Exception {
connection = DriverManager.getConnection(url, username, password);
}
public int saveData(String name) throws Exception {
PreparedStatement preparedStatement = connection.prepareStatement(name);
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
String row = resultSet.getString("NAME");
return resultSet.getRow();
}
public static void main(String[] args) throws Exception {
Processor processor = new Processor();
int row = processor.saveData(new String("INSERT INTO NAMES (name) VALUES (nameTable)"));
}
}
The url, username and password are setup but not shown in the code. I can connect to the Oracle database and persist the data. However, the problem arises when calling resultSet.getString("NAME"). The following Exception is shown:
ORA-009900: invalid SQL statement
java.sql.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
When executing the following code:
ResultSet resultSet = connection.createStatement().executeQuery("SELECT NAME FROM NAMES"));
resultSet.next();
String name = resultSet.getString("NAME");
This works. I have also executed in the SQL describe NAMES and the name attribute is displayed as NAME.
The issue is something to do with the PreparedStatement object returning the ResultSet data.
Any ideas?
EDIT:
ORA-00900: invalid SQL statement
java.sql.SQLSyntaxErrorException
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:675)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Odscrarr.doODNY(T48COdscrarr.java:98)
at oracle.jdbc.driver.T4CPreparedStatement.doDescribe(T4CPreparedStatement.java:818)
at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleResultSetImpl.java:3711)
at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2799)
at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:498)
at com.example.ProcessorTest.testExecuteInsert(ProcessorTest.java:14)
Your saveData method is the cause because an INSERT does not produce a ResultSet, so executeQuery will produce an error, as there will be no ResultSet.
Also you should only use connection.prepareCall(String) for executing stored procedures, not for other types of statements. For a prepared statement you should use connection.prepareStatement(String).
Change your code to:
public int saveData(String name) throws Exception {
PreparedStatement preparedStatement = connection.prepareStatement(name);
preparedStatement.setString(1, name);
return preparedStatement.executeUpdate();
}
BTW: I hope you are aware that this method uses the parameter name both for the query and as the parameter for the query (which really does not make a lot of sense).
And finally, the new String(...) you do in your main is totally unnecessary.
First of all this line of code
int row = processor.saveData(new String("INSERT INTO NAMES (name) VALUES (nameTable)"));
As you have specified that the method saveData() takes argument as String so there is no need of any new String(...) here and moreover you are using PreparedStatement so you can use parameterized query something like this
int row = processor.saveData("INSERT INTO NAMES (name) VALUES (?)");
Then you can use this statement in saveData()
preparedStatement.setString(1, "name");
Finally you are updating the table not quering it so change this
preparedStatement.executeQuery();
to
return preparedStatement.executeUpdate();
One more thing you should be very specific about your method name. You should always name a method based on what it is going to do. Like saveData() here must be used only for saving data not querying the data as you were trying to do by using the ResultSet. If you want to retrieve the data then use some other method.

Categories

Resources