When I delete the else if part it works fine, but if I keep it, it gives me java.sql.SQLException: No data found And obviously I want my String variable get the value from database cell IF the cell wasn't emtpy.
String updatedby = ""; // Outside of While loop
// Inside the while loop.
if(rs.getString("UpdatedBy") == null)
{ updatedby = ""; }
else if(rs.getString("UpdatedBy") != null)
{ updatedby = rs.getString("UpdatedBy"); updatedby = updatedby.trim(); }
I'm confused.
Why don't you just call it once?
updatedby = rs.getString("UpdatedBy");
updatedby = (updatedby == null ? "" : updatedby.trim());
Less overhead that way. And less code. Cleaner.
You should be able to use ResultSet.wasNull() which reports whether the last column read had a value of SQL NULL. Something like
updatedBy = rs.getString("UpdatedBy");
if (!rs.wasNull()) {
updatedBy = updatedBy.trim();
} else {
updatedBy = "";
}
Related
i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.
I've researched can't find any relevant info. I have a result set that give me back distinct tagId's their can be multiple tagIds for same accountId's.
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
// plenty of other fields being store locally
}
I need to store first accoundId(which is being done) & every subsequent iteration compare it with the previous Id to check for equality or not(if so same account).
I tried this and it failed horribly, after first iteration they'll continually be equal & I must be DUMB bc i though as long as I compare them before assignment global guy(previousId) should be holding the prior value.
String previousId = null;
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
previousId = accountId;
}
Anyway I wanted my workflow to go something as follows:
while(result_set.next()){
if (previousId = null) {
// this would be the first iteration
}
else if (previousId.equals(accountId) {
// go here
} else {
// go here
}
}
If I've understood you well, this should work..
String previousId = null;
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
if (previousId == null) {
// this would be the first iteration
} else if (previousId.equals(accountId) {
// go here
} else {
// go here
}
previousId = accountId;
}
I'm using JPA, hibernate 3.
String sqlQuery = " FROM TraceEntityVO where lotNumber =:lotNumber and mfrLocId=:mfrLocId and mfrDate=:mfrDate and qtyInitial=:qtyInitial and expDate=:expDate";
Query query = entityManager.createQuery(sqlQuery)
.setParameter("lotNumber", traceEntityVO.getLotNumber())
.setParameter("mfrLocId", traceEntityVO.getMfrLocId())
.setParameter("mfrDate", traceEntityVO.getMfrDate())
.setParameter("qtyInitial", traceEntityVO.getQtyInitial())
.setParameter("expDate", traceEntityVO.getExpDate());
This query works like a charm when the there were no empty or null values. But there could be possible of null or empty value for traceEntityVO.getLotNumber(),traceEntityVO.getMfrLocId(),traceEntityVO.getExpDate().
In this case the value 'null' or '' is checked against the variable instead of is null condition. How do I handle when I'm not sure about the parameter value, either null or empty?
I don't want to construct the query dynamically based on the values if empty or null.
Is this possible?
Thanks in advance..
I think you really can't do that without a dynamic query.
Building such a query however is easy with the criteria API (hibernate) (JPA), did you consider it?
I hope following code will sort your problem. Assuming getMfrDate and getExpDate will return Date Object and others either Number or String objects. But you can modify IsEmpty according to return types.
String sqlQuery = " FROM TraceEntityVO where lotNumber :lotNumber
and mfrLocId :mfrLocId and mfrDate :mfrDate and qtyInitial :qtyInitial and
expDate :expDate";
Query query = entityManager.createQuery(sqlQuery)
.setParameter("lotNumber", isEmpty(traceEntityVO.getLotNumber()))
.setParameter("mfrLocId", isEmpty(traceEntityVO.getMfrLocId()))
.setParameter("mfrDate", isEmpty(traceEntityVO.getMfrDate()))
.setParameter("qtyInitial", isEmpty(traceEntityVO.getQtyInitial()))
.setParameter("expDate", isEmpty(traceEntityVO.getExpDate()));
private String isEmpty(Object obj) {
if(obj!=null) {
if (obj instanceof java.util.Date) {
return " = to_date('"+obj.toString()+"') ";
} else if(obj instanceof String) {
return " = '"+obj.toString()+"' ";
} else if (obj instanceof Integer) {
return " = "+obj.toString()+" ";
}
}
return new String(" is null ");
}
How can I detect when a json value is null?
for example: [{"username":null},{"username":"null"}]
The first case represents an unexisting username and the second a user named "null". But if you try to retrieve them both values result in the string "null"
JSONObject json = new JSONObject("{\"hello\":null}");
json.put("bye", JSONObject.NULL);
Log.e("LOG", json.toString());
Log.e("LOG", "hello="+json.getString("hello") + " is null? "
+ (json.getString("hello") == null));
Log.e("LOG", "bye="+json.getString("bye") + " is null? "
+ (json.getString("bye") == null));
The log output is
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
Try with json.isNull( "field-name" ).
Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
Because JSONObject#getString returns a value if the given key exists, it is not null by definition. This is the reason JSONObject.NULL exists: to represent a null JSON value.
json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
For android it will raise an JSONException if no such mapping exists. So you can't call this method directly.
json.getString("bye")
if you data can be empty(may not exist the key), try
json.optString("bye","callback string");
or
json.optString("bye");
instead.
In your demo code, the
JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
this you get is String "null" not null.
your shoud use
if(json.isNull("hello")) {
helloStr = null;
} else {
helloStr = json.getString("hello");
}
first check with isNull()....if cant work then try belows
and also you have JSONObject.NULL to check null value...
if ((resultObject.has("username")
&& null != resultObject.getString("username")
&& resultObject.getString("username").trim().length() != 0)
{
//not null
}
and in your case also check resultObject.getString("username").trim().eqauls("null")
If you must parse json first and handle object later, let try this
Parser
Object data = json.get("username");
Handler
if (data instanceof Integer || data instanceof Double || data instanceof Long) {
// handle number ;
} else if (data instanceof String) {
// hanle string;
} else if (data == JSONObject.NULL) {
// hanle null;
}
Here's a helper method I use so that I can get JSON strings with only one line of code:
public String getJsonString(JSONObject jso, String field) {
if(jso.isNull(field))
return null;
else
try {
return jso.getString(field);
}
catch(Exception ex) {
LogHelper.e("model", "Error parsing value");
return null;
}
}
and then something like this:
String mFirstName = getJsonString(jsonObject, "first_name");
would give you your string value or safely set your string variable to null. I use Gson whenever I can to avoid pitfalls like these. It handles null values much better in my opinion.
i have an xml file with attributes like this:
<folder name = 'somename' description = ''/>
i want to display the description attribute as 'null' but it force closes and throws a FATAL Exception main in the LogCat.
i have this code below at the startElement() method
if (localName.equalsIgnoreCase("folder")) {
/** Get attribute value */
if(attributes.getValue("description")== "null"){
parseList.setFolderdesc(null);
}else{
String desc = attributes.getValue("description");
parseList.setFolderdesc(desc);
}
i tried this code but no luck...
how will i solve this without changing my xml file?
try with the following code
String desc = null;
try{
desc = attributes.getValue("description");
if((desc == null) || (desc.length()<=0)){
desc = null;
}
}catch(Exception ex){
desc = null;
}
if(parseList != null){
parseList.setFolderdesc(desc);
}
This code doesn't do what you expect:
if (attributes.getValue("description") == "null") {
You are comparing the attribute value with the String "null" not with a java null. (And you are testing strings the unsafe way too! Strings should be tested for equality using String.equals() not the == operator.)
That test should be written as follows:
if (attributes.getValue("description") == null) {
or better still:
if (attributes.getValue("description") == null ||
attributes.getValue("description").isEmpty()) {
(I'm not sure whether this will fix you problem, because I don't understand your problem description.)