I am getting an error saying that some string is missing inside the ResultSet returned from the database. Now I have a problem: how can I see what is inside the ResultSet?
Examples available on google are with explicit methods like getString() or getInt() but thse methods suppose you know what you are looking for. What I actually need - to look what elements are available inside my ResultSet.
Something like when I issue the resultSet.toString() command, and it would show me some kind of map with variable names - is it possible?
EDIT:
If it is useful - below is a piece of code:
public Project mapRow(ResultSet resultSet, int i) throws SQLException {
System.out.println(resultSet.toString());
return new Project(resultSet.getInt("project_id"), resultSet.getString("project_name"),
resultSet.getString("project_description"), new Category(resultSet.getInt("category_id"),
resultSet.getString("category_name")),
resultSet.getString("project_link"), resultSet.getString("project_qa"));
}
Error:
Caused by: org.postgresql.util.PSQLException: The column name category_id was not found in this ResultSet.
The ResultSet contains no element after you execute a statement. To get the first row of information, you need to do rs.next().
Here is a simple iteration through the ResultSet values.
boolean hasValue = false;
while(resultSet.next())
{
hasValue = true;
out.println(resultSet.getString("column_name");
out.println(resultSet.getInt("column_name");
}
if(hasValue)
out.println("Result set has values inside of it");
else out.println("Result set has no values inside of it");
As long as you have some values inside your resultSet variable, you need to iterate it to get the next value. By default, after the query is executed, you have no value inside of it because it might have no value.
Edit:
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
columnName[i-1] = metaData.getColumnLabel(i));
}
This gives you the column names, if this is what you want.
Obtain a ResultSetMetaData from the result set via ResultSet.getMetaData().
The ResultSetMetaData has methods getColumnCount and getColumnName to enumerate the column names.
Related
I am using JDBC and PostgreSQL as database, I was trying to create a logic in such a way that we can fetch all the data from a table, whatever table name user gives in the input it should get fetched, but the issue here is, I don't know how to do that.
Whenever we used to fetch table data from the database we are required to specify the the type of data we are getting on every index while we use ResultSet.
How to overcome from this hardcoded need of providing this metadata and make our code more general for any table with any number of columns and with any type
My code:
Statement sttm = con1.createStatement();
System.out.println("Enter table name (usertable)");
String name = sc.next();
String tableData="";
String qu = "select * from "+name;
ResultSet rs =sttm.executeQuery(qu);
while(rs.next()) {
// here we need to define the type by writing .getInt or getString
tableData = rs.getInt(1)+":"+rs.getString(2)+":"+rs.getInt(3);
System.out.println(tableData);
}
System.out.println("*********---------***********-----------**********");
sttm.close();
Anyone please suggest me some way to do it.
You can use ResultSet.getObject(int). getObject will automatically retrieve the data in the most appropriate Java type for the SQL datatype of the column.
To retrieve the number of columns, you can use ResultSet.getMetaData(), and then use ResultSetMetaData.getColumnCount() to retrieve the number of columns.
In short, to print all columns of all rows, you can do something like:
try (ResultSet rs = stmt.executeQuery(qu)) {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
StringBuilder tableData = new StringBuilder();
for (int colIdx = 1; colIdx <= columnCount; colIdx++) {
tableData.append(rs.getObject(colIdx));
if (colIdx != columnCount) {
tableData.append(':');
}
}
System.out.println(TableData);
}
}
You can also use ResultSetMetaData to get more information on the columns of the result set, for example if you need specific handling for certain types of columns. You can use getColumnType to get the java.sql.Types value of the column, or getColumnTypeName to get the type name in the database, or getColumnClassName to get the name of the class returned by ResultSet.getObject(int/String), etc.
However, as Sorin pointed out in the comments, accepting user input and concatenating it into a query string like you're currently doing, makes you vulnerable to SQL injection. Unfortunately, it is not possible to parameterize object names, but you can mitigate this risk somewhat by 1) checking the table against the database metadata (e.g. DatabaseMetaData.getTables), and 2) using Statement.enquoteIdentifier (though this won't necessarily protect you against all forms of injection).
If you want to print data of any table from a database then check my github project over CRUD java MySQL
https://github.com/gptshubham595/jdbc_mysql_CRUD-JAVA-
These are implemented
I want to get some informations in my SQL base, but i don't know how to. I have already used this following code :
String pseudo = null;
String query = "select * from UsersInfos where Pseudo=?"
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, pseudo);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
pseudo = rs.getString("Pseudo");
}
System.out.println(pseudo);
But it returns me null of
System.out.println(pseudo);
I want to get some informations, not set them, well can some one helps me please ?
Your result set is coming back empty. In other words, the assignment pseudo = rs.getString("Pseudo") never took place.
The reason the result set is empty (i.e. contains no records) is due to the WHERE clause:
select * from UsersInfos where Pseudo=null
The comparison of any value in the Pseudo column to null will be either null or false (depending on your particular RDBMS). This means that no records will match.
How can I use resultset to get me the minimum, average or maximum value from a mysql database column?
I have a prepared statement sql constant string = Select avg(EntryValues) from Entries;
I know I need to use a resultset.getString(EntryValues) but I dont know how to build the java method that would return the actual average value from that resultset.next() loop thing...
Could you please help me?
Get a statement from your connection
use the statement.executeQuery() method to invoke your query and assign it to your ResultSet, e.g.
ResultSet rs = statement.executeQuery("SELECT AVG(EntryValues) FROM Entries");
Your result is one simple 'row' therefore you can use
if(rs.next()) { // check if a result was returned
String avg = rs.getString(1); // get your result
}
If your result contains multiple rows you'll have to use a while-loop for example to iterate through all the result entries:
while(rs.next()) {
// do your thing
}
Hope this helpes, have Fun!
I insert some values into a database using a PreparedStatement, but it seems, that i cannot retrieve the last insert id in that case.
I try to use the same statement as i use for Statements (below) but it doent work. It says, that .executeQuery() cannot take arguments in this case.
In fact, i don't exactly need the last insert id, the number of affected rows will do, but how do i get that? I thought PreparedStatement's .executeUpdate() method would return the number of affected rows, but it apparently it does not.
Here is the method.
public static int getLastInsertId(Statement stmt) throws SQLException {
String sql = "SELECT SCOPE_IDENTITY() AS id";
ResultSet rs = stmt.executeQuery(sql);
int id = 0;
while (rs.next()) {
id = rs.getInt("id");
}
return id;
}
Thank you in advance.
A PreparedStatement's executeUpdate method DOES indeed return the number of affected rows...
Does anyone know a better way of getting the number of rows in a Java resultset returned from a MySQL database? The resultset returned is not going to be the total number of rows read from the database so I don't think I can use SQL's COUNT aggregate function.
public static int getResultSetRowCount(ResultSet resultSet) {
int size = 0;
try {
resultSet.last();
size = resultSet.getRow();
resultSet.beforeFirst();
}
catch(Exception ex) {
return 0;
}
return size;
}
A better answer is to forget about the number of rows until you've successfully loaded the ResultSet into an object or collection. You can keep the count of the number of rows with either of those options.
It's important to close ResultSets (and all SQL resources like Connection and Statement) in the narrowest method scope possible. That means not passing ResultSet out of the persistence layer. Better to get the number of rows using a Collection size() call.
Stop thinking about databases and start thinking in terms of objects. Java's an object-oriented language.
You can execute
SELECT FOUND_ROWS()
immediately after executing your SELECT statement to find the row count.
If you are using Java 6 you can use the JDBC4ResultSet class which has the getUpdateCount method that returns the number of the lines affected by a SQL Statement even for a Select Statement.
See below the example code:
PreparedStatement ps = con.prepareStatement("select * from any_table ...");
JDBC4ResultSet rs = (JDBC4ResultSet)ps.executeQuery();
int rowNumber = rs.getUpdateCount();
I hope that this help!
You can always use SELECT COUNT() with the same exact conditions, before making the actual SELECT.
Here is my solution to this question (since I mostly want the number of records returned to build an array or something similar): Use a collection such as Vector<T> instead.
public Vector<T> getRecords(){
Vector<T> records = new Vector<T>();
init_conn_and_stmt_and_rs();
try {
rs = stmt.executeQuery("SELECT * FROM `table` WHERE `something` = 0");
while(rs.next()){
// Load the Vector here.
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close_rs_and_stmt_and_conn();
}
return records;
}
Clean and simple, no? Works for any size record set returned (no need to know the size before hand) and makes all the List methods available.
This has served me well for a time now, but if someone sees a flaw in this, please let me know. Always want to make my practices better, ya know.
You can also use the following way to get the total records in the resultSet:
statement = connect.createStatement();
resultSet = statement.executeQuery(sqlStatement);
resultSet.last();
int count = resultSet.getRow();
System.out.println(count);
count is the total returned rows for your result set. ;)