This question may be very easy, but I´m not exactly sure, how to do this.
I want to store the return value from my SQL-statement in a variable.
int i;
String name = "Testuser";
First i create my var. Now I want to store the value, which is saved in my Database (named Data) in a field called "money" , with the key "Testuser" into my variable i.
Now you have already the instance of statement you can do something like that
int i;
ResultSet resultat = null;
resultat = statement.executeQuery("SELECT money FROM data WHERE id=1;");//for example the value of the field money in the row who has id=1
if(resultat.next()){ // you check if the query returned a value
i=resultat.getInt("money"); // the name of the column
}
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 have a java method like this one below:
public String qE (String query, String selector) throws QSLException, IOException{
//I get my sqlQuery from properties
String sqlQuery = properties.getPRoperty(query);
//sqlQuery = SELECT count(?) FROM employees WHERE ? is not null
PreparedStatement ps = conn.preparedStatement(sqlQuery);
ps.setFetchSize(100);
ps.setString(1,selector);
ps.setString(2,selector);
ResultSet rs = ps.executeQuery();
String rs = "";
while(rs.next()){
queryValue = rs.getString(1);
}
return queryValue;
}
When I run it with parameters
qe(employees, second_name)
then this query should be executed:
SELECT count(second_name)
FROM employees
WHERE second_name is not null
The problem is that non of employees has second name and I should get 0 and the whole method should return 0 but I always get diffrent number greater than zero.
Can anyone tell me why this doesn't return 0 but always diffrent number like i.e. 2399?
A ? represents a value not an object name, so it is equivalent to using
SELECT count('second_name')
FROM employees
WHERE 'second_name' is not null
Which is always true and is always counted. In other words, your query counts all rows in table employees.
You cannot use parameters to parameterize object names. If you really need to do this dynamically, you will need to construct the query dynamically (by concatenating the name in the query string). Just be sure to guard yourself against SQL injection if you do that (eg by checking the name against a white list or comparing explicitly to the database metadata).
I have two sqlite tables in a specific database. I want to add the same data to both tables but on the second table I want to also store the ID of that entry in the first table.
What I do is add the entry ('Name', 'Description') to the first table then query to get the 'ID2' value then add the entry and the ID2 number into my second table after (Put ID2 in as ID3). I always rawquery to get my last entry's 'ID2' column value.
I have this working in the sense that it doesnt crash and does add a value to my second table BUT its isnt adding the value but instead some sort of reference which I do not understand so cant look up.
I would like a solution to get the the last 'ID2' value of my first table and insert it into my second table in 'ID3' column ALSO I would like an explanation of why what I have below is wrong.
Please reference my Java code below and screenshots of my two databases (the second showing the reference code not the value I want)
Thank you so much.
public boolean insetTheme(String name2,String Description){
SQLiteDatabase Mydb =this.getWritableDatabase();
ContentValues newThingAdd = new ContentValues();
newThingAdd.put(COL2_ALLTHEMES,name2);
newThingAdd.put(COL3_ALLTHEMES,Description);
long result = Mydb.insertOrThrow(TABLE_ALLTHEMES,null,newThingAdd);
Cursor res = Mydb.rawQuery("select * from "+TABLE_ALLTHEMES + " where 'ID2'" ,null);
//res.moveToLast();
if (res != null) {
res.move(-1);
}
ContentValues newThingAdd123 = new ContentValues();
newThingAdd123.put(COL2_CURRENTTHEMES,name2);
newThingAdd123.put(COL3_CURRENTTHEMES,Description);
newThingAdd123.put("ID3",res.toString());
long result2 = Mydb.insertOrThrow(TABLE_CURRENTTHEMES,null,newThingAdd123);
if ((result==-1)&(result2==-1))
return false;
else
return true;
}
First Table
Second Table
res is a Cursor so calling toString() on it won't give you what you want.
You need to use res.getString(0) or similar with the specific method based on what type the value is (String, int, boolean etc) and the number being the column number, for example, if the value you want is the third column that would be returned in the query, use res.getString(2) to get the value.
If I made a query like this:
Cursor cursor = Mydb.rawQuery("SELECT * FROM table_1");
and table_1 had 3 columns:
id, name, date
if I wanted the name, I would use
String name = cursor.getString(1);
Hopefully this is what you were after.
I have written a code to insert data from jdbc textfield to mysql DB .
String res ="INSERT INTO reservation(check_in_date,check_out_date,cus_id,room_no,Username,nights,adults,kids) VALUES ('"+Startdate+"','"+Lastdate+"','"+cusNo+"','"+Roomno+"','"+Username+"','"+Nights +"','"+Adults +"','"+Kids +"')";
stm=link.prepareStatement(res);
stm.execute();
In this code Kids variable can be null and I have set its' default value to null in database.
But when I enter data from GUI I should always input values for Kids otherwise I can't insert data to the table.
So I must always enter zero to the Kids if I don't need to use that field.
Is there any way to insert data without input Kids when there is no need to use that field?
You are using PreparedStatement incorrectly. You should not concatenate values into a query, but use parameter placeholders instead. This prevents SQL injection and it is usually cleaner.
You can set values to null this way.
String res = "INSERT INTO reservation(check_in_date,check_out_date,cus_id,room_no,Username,nights,adults,kids)"
+ " VALUES (?,?,?,?,?,?,?,?)";
try (PreparedStatement stm=link.prepareStatement(res)) {
stmt.setDate(1, startDate);
// ... other variables
// Option 1, assuming kids is an object (eg Integer)
stm.setObject(7, kids);
// Option 2, kids is int and other condition used to determine if null,
// explicitly set null or set value:
if (kidsIsNull) {
stm.setNull(7, Types.INTEGER);
} else {
stm.setInt(7, kids);
}
stm.executeUpdate();
}
As you are using prepare statement you can add logic to use setNull method for preparedStatement something like this :
if( kids == null){
stm.setNull(#ParamerterNo ,java.sql.Types.INTEGER);
}else{
stm.setInt(#ParamerterNo ,kids);
}
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.