sql retrieval value in java is null - java

I inserted one column in sql with null value from java.while retrieving back it is not working with null.i also checked with string.length().But when i printed the value in System.out. the value is showing as null (just null).when i checked it with condition it is not entering into loop.
String id ="1234";
String name="pratap";
String gender=null;
String email=null;
String service="GOOGLE";
log.info(id+name+gender+email) //output is 1234pratapnullnull
String insert = "INSERT INTO oauthuser VALUES('"+id+"','"+name+"','"+gender+"','"+email+"','"+service"')";
In the retrieval
query ="Select * FROM oauthuser where id="+"'"+id+"'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
id=rs.getString(1);
name=rs.getString(2);
gender=rs.getString(3);
email=rs.getString(4);
service_provider_name=rs.getString(5);
System.out.println(gender+email+name);//output is nullnullpratap
}
if(gender!="male" && gender!="female")
System.out.println("it is printing");
if(gender==null)
System.out.println("it is not printing");
con.close();

From your somewhat cryptic description of the problem I suspect that you may have inserted the string "null" rather than the SQL NULL value. The two are not the same (very different, in fact).
edit Having reviewed the code, this is exactly what happens. Take, for example, gender:
String gender = null;
...'"+gender+"',...
The above converts it to 'null' (i.e. the SQL string "null"), and inserts that into the database.
My basic advice would be to read up on PreparedStatement and use that instead of building the SQL query bit by bit as you're doing right now.
Finally, the following is broken:
if(gender!="male" && gender!="female")
This should be
if(!gender.equals("male") && !gender.equals("female"))

you can try "null" instead of NULL , but better to show us the code
after your update
remove + sign from your query like this
String id ="1234";
String name="pratap";
String gender="null";
String email="null";
String service="GOOGLE";
log.info(id+name+gender+email) //output is 1234pratapnullnull
String insert = "INSERT INTO oauthuser VALUES('"id"','"name"','"gender"','"email"','"service"')"
and when you select , modify like this
if(gender.equals("null"))
System.out.println("it is not printing");

Maybe your value is not null but "null" string? Start your application in debug, put break point and check it.

Related

How to use textfield input in mysql SELECT query

I am using Java netbeans and mysql. I want to check whether the value entered by the user in a textfield tf is already present in the mysql table or not.
String query1="SELECT * FROM trytable WHERE name='8'";
ResultSet rs=stmt.executeQuery(query1);
if(rs.isBeforeFirst()==true){JOptionPane.showMessageDialog(null,"already");}
In the above code in place of 8 I want to give the value that the user input in the form and then check whether that value already exist in form or not.
Please help me in the first line . Thanks
You should use a PreparedStatement instead of a regular statement. This is more secure than a normal Statement and allows you to avoid SQL injection issues.
You would change your query like so:
String query = "SELECT * FROM trytable WHERE name='?';";
Note the ? at the end of the query. This can be replaced later in your code when setting up the PreparedStatement:
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, userInput);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) System.out.println("Record exists!");
Here, you are telling the prepared statement to replace the first ? in the query, with the value of userInput. So, if the user inputs a 3, the query that gets executed would be SELECT * FROM trytable WHERE name=3;.
Also note that rs.next() returns true if the query returns any results, so that would be the proper way to determine if the record exists.
ResultSet is like a table, it has a cursor. At the beginning the cursor is above the first row so isBeforeFirst() will always return true even there are no results in the ResultSet.
In order to retrieve results you need to move the cursor to the next row, to do that you can use,
rs.next()
If the cursor moved to the next row successfully (which means there are more results) it will return true otherwise false. As you only need the first result you can also use,
rs.first()
to confirm there are data available in the returned ResultSet.
Try,
if (rs.first()) {
JOptionPane.showMessageDialog(null, "already");
}
This is the final code will is working absolutely fine.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT * FROM table_name WHERE name=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,jtf.getText());
ResultSet rs = preparedStatement.executeQuery();
if(rs.next()==true){
JOptionPane.showMessageDialog(null,"Value already exist");
}
else{
JOptionPane.showMessageDialog(null,"Value not present");
String query1="INSERT INTO table_name(col_name) VALUES (?)";
preparedStatement = conn.prepareStatement(query1);
preparedStatement.setString(1,jtf.getText());
preparedStatement.execute();
JOptionPane.showMessageDialog(null,"DONE");
}
rs.close();
preparedStatement.close();
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
}

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

How to set variables into a JDBC statement?

It works when i try to insert variables for example :
String insertStr="INSERT INTO table1(username1,password1) VALUES(\"john\",\"password\")";
but unable to insert using variable
String a=username.getText();
String b=password.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db1","root","");
Statement stmt=con.createStatement();
String insertStr="INSERT INTO table1(username1,password1) VALUES(a,b);";
stmt.executeUpdate(insertStr);
} catch (Exception e) { }
Use [PreparedStatement][1] instead of your way, because your way can be a victim of SQL Injection or Syntax errors :
String insertStr = "INSERT INTO table1(username1,password1) VALUES(?, ?)";
try (PreparedStatement pst = con.prepareStatement(insertStr)) {
pst.setString(1, a);
pst.setString(2, b);
pst.executeUpdate();
}
For reason of security I don't suggest to get password with getText(), instead use getPassword(), so you can use :
pst.setString(1, username.getText());
pst.setString(2, new String(passwordField.getPassword()));
Take a look at this :
getText() vs getPassword()
Why getText() in JPasswordField was deprecated?
[1]: https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html
Since you are inserting "a" and "b" as String, not their variable values.
String insertStr="INSERT INTO table1(username1,password1) VALUES("+a+","+b+");";
should do it, but I would recommend to use a prepared statement here: https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
The most common way to insert variable values into sql is to use the PreparedStatement Object
With this object, you can add variable values into a SQL Query without fearing of SQL injection.
Here an example of PreparedStatement :
//[Connection initialized before]
String insertStr="INSERT INTO table1(username1,password1) VALUES(?,?);";
PreparedStatement myInsert = myConnectionVariable.prepareStatement(insertStr); // Your db will prepare this sql query
myInsert.setString(1, a); //depending on type you want to insert , you have to specify the position of your argument inserted (starting at 1)
myInsert.setString(2, b); // Here we set the 2nd '?' with your String b
myInsert.executeUpdate(); // It will returns the number of affected row (Works for UPDATE,INSERT,DELETE,etc...)
//You can use executeQuery() function of PreparedStatement for your SELECT queries
This is safer than using String concatenation like this : VALUES("+a+","+b+");
Take a look at Java Doc for more information ;)

Parameter index out of range (1 > number of parameters, which is 0)

I get this error, Can anyone help me in finding my mistake in the query?
public boolean populateLeagues(String leaguename, String password){
Connect connect = new Connect();
Connection conn = connect.Connection();
Statement stmt = conn.createStatement();
String query = "INSERT INTO users VALUES('" + leaguename + "')";
stmt.executeUpdate(query);
conn.close();
}
AS #Jon Skeet says, use a prepared statement and inject parameters into. In this way you don't have to figure out all hassles about sql injection and data format(think about using a query like the one you provide to store datetime globally).
Probably leaguename value is null. Remember that default value for string type isn't the empty strin but null
You use single quote around leaguename, since we don't know how leaguename is formatted, that might lead to errors

Handling the null value from a resultset

I currently have a result set returned, and in one of the columns the string value may be null (I mean no values at all). I have a condition to implement like following
rs = st.executeQuery(selectSQL);
output = rs.getString("column");
Since the column may be null in the database, the rs.getString() will throw a NullPointerException when the column is null. If column is null, I want the output to be an empty string like output = "";. I can't check if(rs.getString("column) != null either. How can I tackle this situation?
My real problem:
try {
rs = st.executeQuery(sql);
int i = 0;
while (rs.next()) {
output[i] = rs.getString(column);
// column field in the database contains multiple results, but sometimes
// may be null
i++;
}
} catch (SQLException e) {
e.printStackTrace();
// other than tracing the exception i want to fill the array too
}
return output;
Now, if one of the column values contains no value, i.e. null, I want output[i] defined as N/A. This problem stems from the fact that the column field is NULL allowed in the database. And sorry for telling you that it's a NPE, while in fact it's a SQLException.
Since the column may be null in the
database, the rs.getString() will
throw a NullPointerException()
No.
rs.getString will not throw NullPointer if the column is present in the selected result set (SELECT query columns)
For a particular record if value for the 'comumn is null in db, you must do something like this -
String myValue = rs.getString("myColumn");
if (rs.wasNull()) {
myValue = ""; // set it to empty string as you desire.
}
You may want to refer to wasNull() documentation -
From java.sql.ResultSet
boolean wasNull() throws SQLException;
* Reports whether
* the last column read had a value of SQL <code>NULL</code>.
* Note that you must first call one of the getter methods
* on a column to try to read its value and then call
* the method <code>wasNull</code> to see if the value read was
* SQL <code>NULL</code>.
*
* #return <code>true</code> if the last column value read was SQL
* <code>NULL</code> and <code>false</code> otherwise
* #exception SQLException if a database access error occurs or this method is
* called on a closed result set
*/
output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null`
if(output == null){// if you fetched null value then initialize output with blank string
output= "";
}
The description of the getString() method says the following:
the column value; if the value is SQL NULL, the value returned is null
That means your problem is not that the String value is null, rather some other
object is, perhaps your ResultSet or maybe you closed the connection or something
like this. Provide the stack trace, that would help.
I was able to do this:
String a;
if(rs.getString("column") != null)
{
a = "Hello world!";
}
else
{
a = "Bye world!";
}
The String being null is a very good chance, but when you see values in your table, yet a null is printed by the ResultSet, it might mean that the connection was closed before the value of ResultSet was used.
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
con.close();
System.out.println(rs.getString(1));
Would print null even if there are values.
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs.getString(1));
con.close();
Wouldn't print null if there are values in the table.
The code should be like given below
String selectSQL = "SELECT IFNULL(tbl.column, \"\") AS column FROM MySQL_table AS tbl";
Statement st = ...;
Result set rs = st.executeQuery(selectSQL);
To treat validation when a field is null in the database, you could add the following condition.
String name = (oRs.getString ("name_column"))! = Null? oRs.getString ("name_column"): "";
with this you can validate when a field is null and do not mark an exception.
I came across with the same issue. But I believe , handling null in the sql is not a good option. such things should be handled in java program for better performance.
secondly , rs.getString("column") != NULL is also not a good option as you are comparing string's reference not value. better to use .equals() method while checking null or isEmpty() method. Again, with this you can use null check, that is fine.
You can simply use-
rs = st.executeQuery(selectSQL);
output = rs.getString("column");
if(!output.isEmpty()) {
//
}
In MySQL faced issue with-
output!=null
output!=""
But output.isEmpty() worked for rs.getString().

Categories

Resources