How to convert prepared statement into String [duplicate] - java

This question already has answers here:
Get value from a ResultSet by name
(2 answers)
Closed 1 year ago.
I am trying to set a string value into DB using prepared statement and Result Set. But it inserts into DB row this "com.mysql.cj.jdbc.result.ResultSetImpl#fcd6521"
PreparedStatement check = connection.prepareStatement(
"SELECT buildingName FROM building GROUP BY buildingId HAVING buildingId = ?");
check.setInt(1, building_id);
ResultSet rs = check.executeQuery();
insert.setString(1, String.valueOf(rs));
insert.executeUpdate();

I think that you need to read the tutorial indicated by #user16320675
A ResultSet is a type of set. It has to be accessed like that:
//if you expects receive only one buildName you use a simple if, otherwise you have to use a loop and a list or something like that
String text;
if(rs.next()){
text = rs.getString(0);
}
//index it's related to buildingName

Related

I'm trying to print values from a table using PreparedStatement in Java, but I get column names instead of values [duplicate]

This question already has answers here:
Having a Column name as Input Parameter of a PreparedStatement
(1 answer)
PreparedStatement: Can I supply the column name as parameter?
(4 answers)
Dynamic column name using prepared statement + sql query with variable containing 's
(1 answer)
Closed 1 year ago.
I'm using below code to print columns from a tables using PreparedStatement:
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost/javatesting";
Connection con = DriverManager.getConnection(url, "root", "password");
PreparedStatement preparedStatement = con.prepareStatement("Select ?,?,? from test where salary> ?");
preparedStatement.setString(1, "name");
preparedStatement.setString(2, "dept");
preparedStatement.setString(3, "salary");
preparedStatement.setInt(4, 25000);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("name")+","+resultSet.getString("dept")+","+
resultSet.getString("salary"));
}
The output of above code looks like this:
name,dept,salary
name,dept,salary
name,dept,salary
There are actual(valid) values in the table, still I end up printing the column names instead of values.
The output that I'm expecting to get printed looks something like this:
Ben,IT,30000
Marie,BPO,35000
Subash,IT,30000
The problem is that the PreparedStatement escapes the values that are passed via a ?.
So name becomes "name" and SELECT "name" always returns name.
You should change your query:
SELECT name, dept, salary FROM test WHERE salary > ?
preparedStatement.setInt(1, 25000);

java.sql.SQLException: Closed Resultset: next [duplicate]

This question already has an answer here:
SQLException: the result set is closed
(1 answer)
Closed 3 years ago.
I didn't find the reason for a SQLExeption, I got it at while(dbrs.next()). It is simple, it was working, but after update to Oracle Server 19, I got this error. I got still a result set in Oracle Developer with the same account.
Statement st = conn.createStatement();
if (Oracle){
ResultSet dbrs = st.executeQuery("select table_name from all_tables");
while(dbrs.next()){
if (dbrs.getString(1).equals(G_IN)){
st.execute("DROP TABLE "+G_IN);
System.out.println(G_IN+" gelöscht");
}
}
dbrs.close();
}else{
String loeschen="DROP TABLE IF EXISTS \"" + G_IN +"\"";
System.out.println(loeschen);
st.execute( loeschen );
}
You shouldn't reuse a Statement object as is the case in your while loop. To execute a new query, you need to use a new Statement object.
Replace
st.execute("DROP TABLE "+G_IN);
with
conn.createStatement().execute("DROP TABLE "+G_IN);
and it should work.

JDBC PreparedStatement with ? for Columnname won't work [duplicate]

This question already has answers here:
Variable column names using prepared statements
(7 answers)
Closed 4 years ago.
In a university task I'm using JDBC to access a database. I wrote a finder-method that could find objects in a table by any value in any column that has integer values.
public ResultSet findSampleByAnyCol(String colName, Integer sampleId, Connection con) {
ResultSet rs = null;
String sql = "SELECT * FROM sample WHERE ? = ?";
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setString(1, colName);
pstmt.setInt(2, sampleId);
rs = pstmt.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
return rs;
}
I tested it and I'm sure the problem is that "?" for the colum nname doesn't work. The stack trace says "invalid number". But if I change the SQL statement to SELECT * FROM sample WHERE sampleid = ? it works fine.
Just found the answer here, it´s not possible to do that. The "?" is just for values. To have variable columnnames it´s inevitable to do it with an own string manipulation.

Can you help me to find the error below in the ResultSet rs=stmt....? [duplicate]

This question already has an answer here:
ResultSet is not for INSERT query? Error message: Type mismatch: cannot convert from int to String
(1 answer)
Closed 5 years ago.
I am getting a error on the resultset rs part where netbeans shows the error as
incompatible types:int cannot be converted to resultset
Class.forName("java.sql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=false", "root", "abc");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM patient WHERE Mobile_No='" + mobno + "';"; /*Get the value from the database*/
ResultSet rs = stmt.executeUpdate(query);/*Part where the error is appearing*/
while (rs.next()) {
String Name = rs.getString("Name");
String Age = rs.getString("Age");
String Mobile = rs.getString("Mobile_No");
String gender = rs.getString("Gender");
String symptoms = rs.getString("Symptoms");
model.addRow(new Object[]{Name, Age, Mobile, gender, symptoms});
}
rs.close();
stmt.close();
conn.close();
Use stmt.executeQuery(String sql), it returns ResultSet.
If you want a ResultSet returned you should use executeQuery, not executeUpdate.
The stmt.executeUpdate(query); doesn't fit for an SELECT query.
You need to replace it by stmt.executeQuery(query);
Well the method executeUpdate returns a int not a results set, seen in the documentation here: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
the integer being return being either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
the method you are actually want to use is executeQuery and the documentation for that can be found at:
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
According the Javadoc (https://docs.oracle.com/javase/9/docs/api/java/sql/Statement.html#executeUpdate-java.lang.String-), stmt.executeUpdate(query); returns an int and not a ResultSet object.
From the Javadoc :
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
I think you must use stmt.executeQuery(query); instead, which return the ResultSet you expect. You're doing a SELECT and not an INSERT, UPDATE, or DELETE operation.
I believe people have already answered your question, which is statement.executeUpdate(query) returns the number of how many rows has been affected by executing the query, and you should use statement.executeQuery(query) instead ..
But this part String query = "SELECT * FROM patient WHERE Mobile_No = '" + mobno + "';" is very bad approach, it will leave the door opened for SQL injection, you should use PreparedStatement instead of Statement

java.sql.SQLException : Operation not allowed after ResultSet closed [duplicate]

This question already has answers here:
Getting java.sql.SQLException: Operation not allowed after ResultSet closed
(2 answers)
Closed 4 years ago.
Can anyone point me in the write direction to solve the error: SQLException: Operation not allowed after ResultSet closed
Here is the code i believe the error occurs in
Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";
int candidateNo = 42;
query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
ResultSet ts = stmt.executeQuery(query2);
}
I have tried using resultset rs = null; to create the variable but the error still occurs
You are iterating over the ResultSet bound to a Statement , then while iterating, you are using the exact same Statement object to issue a new query and get and iterate over another ResultSet .
This won't work as long as you are not done with the processing of the first ResultSet, so consider using a distinct Statement object for your second query .
In your code you used 2 ResultSet executing the same Statement object (stmt)concurrently. Use different Statement Objects for both queries.

Categories

Resources