I am checking that submitted data is not null but on simply submitting(no data) it is still inserting in the database and also i have made my columns not null but data is still getting inserted.I don't know why?
IN my Servlet
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
boolean checkd=checknull.value(department);
boolean checkc=checknull.value(company);
boolean checkp=checknull.value(place);
if(checkd==true&&checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
if(status){
PrintWriter out= response.getWriter();
out.print("values have been inserted,"+admin);
response.sendRedirect("inserted.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to insert");
response.sendRedirect("notinsered.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}
This is the java class which is checking
public class checknull {
static boolean ch;
public static boolean value(String check)
{
ch = check != null;
return ch;
}
Modify your checknull class to:
public class checknull
{
// static boolean ch; (You don't need this static variable)
public static boolean value(String check)
{
return check != null && check.length() > 0;
}
}
Also, it's a convention in Java to have class names in UpperCase.
Example:
public class CheckNull
EDIT:
As suggested by Erwin Bolwidt, it's very likely that the database being used here is Oracle, since Oracle equates empty strings and nulls.
Therefore, this answer is only applicable to databases that treat empty strings as nulls (e.g. Oracle).
See: null-vs-empty-string-in-oracle
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'm using CachedRowSet. But when I call the insertRow() method, there is a SQLException failed to insert row.
Here is my code:
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/javapos";
static final String USERNAME = "root";
static final String PASSWORD = "sbc";
public static void main (String [] agr) throws SQLException
{
CachedRowSetImpl rs = new CachedRowSetImpl();
rs.setUrl(DATABASE_URL);
rs.setUsername(USERNAME);
rs.setPassword(PASSWORD);
rs.setCommand("select * from uom order by itemid");
rs.execute();
while(rs.next()){
System.out.println(rs.getString("itemid") + " - " + rs.getString("uom"));
}
rs.moveToInsertRow();
rs.updateString(2,"Sample code");
rs.insertRow();
rs.moveToCurrentRow();
rs.acceptChanges();
}
When you call insertRow(), the Reference Implementation of CachedRowSet performs a check if all required columns have been populated and otherwise it throws an exception (source from Grepcode CachedRowSet.insertRow(), line numbers don't exactly match):
if (onInsertRow == false ||
insertRow.isCompleteRow(RowSetMD) == false) {
throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.failedins").toString());
}
The check is performed in InsertRow.isCompleteRow(RowSetMetaData):
public boolean isCompleteRow(RowSetMetaData RowSetMD) throws SQLException {
for (int i = 0; i < cols; i++) {
if (colsInserted.get(i) == false &&
RowSetMD.isNullable(i + 1) == ResultSetMetaData.columnNoNulls) {
return false;
}
}
return true;
}
In other words, when inserting a row you must provide a value for all columns that are not nullable (this includes the primary key). There seem to be two ways to work around this:
Setting a (random) value. This does require that your primary key is always generated (even if a value is provided).
Explicitly setting the column to null using updateNull. Using setNull doesn't work: it provides the same error, and using setObject(idx, null) results in a NullPointerException
When using your code with these changes I get an SQLException when calling acceptChanges as the implementation doesn't disable autoCommit (it seems to have been commented out), but it does explicitly call commit (which is invalid when in autoCommit). This doesn't seem to be easy to solve, except maybe explicitly providing a connection on execute, or creating your own implementation.
I think these kind of issues actually demonstrate how little the RowSet implementations are actually used (otherwise they would already have been flushed out long ago).
Note however that if this were the actual code you needed and don't need the disconnected characteristics of the CachedRowSet, then you could simply use an updatable result set.
Example:
beginAddRow(crs);
crs.updateString("TABLE_TYPE", "TABLE");
continueAddRow();
crs.updateString("TABLE_TYPE", "INDEX");
endAddRow();
static public CachedRowSet beginAddRow(CachedRowSet crs) throws SQLException {
crs.moveToInsertRow(); // onInsertRow = true
return crs;
}
static public CachedRowSet continueAddRow(CachedRowSet crs) throws SQLException {
crs.insertRow();
crs.moveToCurrentRow();
crs.moveToInsertRow();
return crs;
}
static public CachedRowSet endAddRow(CachedRowSet crs) throws SQLException {
crs.insertRow();
crs.moveToCurrentRow(); // onInsertRow = false;
crs.beforeFirst();
return crs;
}
I am using following code
public boolean addArea(AreaClass area , ArrayList<AreaMarkClass> areaArray)
{
area.id = getNextAreaId();
Log.d("longitude", area.longitude);
Log.d("latitude", area.latitude);
ContentValues initialValues = new ContentValues();
initialValues.put("_id", area.id);
initialValues.put("name", area.name);
initialValues.put("longitude", area.longitude);
initialValues.put("latitude", area.latitude);
initialValues.put("zoomLevel", area.zoomLevel);
initialValues.put("creationDate",area.creationDate);
try
{
mDb.insertOrThrow("TTArea", null, initialValues);
}
area.longitude is a string whose value is obtained by String.value (A Double Value)
Now usually it is something like this 22.323434523464563456
however when i try to retrieve this value
public AreaClass getAreaClassWithAreaId(Integer id)
{
String queryString = "SELECT * FROM TTArea WHERE _id = ?";
Cursor resultSet = mDb.rawQuery(queryString, new String[]{id.toString()});
AreaClass area = new AreaClass();
while(resultSet.moveToNext())
{
area = new AreaClass(
resultSet.getInt(resultSet.getColumnIndex("_id")),
resultSet.getString(resultSet.getColumnIndex("name")),
resultSet.getString(resultSet.getColumnIndex("longitude")),
resultSet.getString(resultSet.getColumnIndex("latitude")),
resultSet.getString(resultSet.getColumnIndex("zoomLevel")),
resultSet.getString(resultSet.getColumnIndex("creationDate"))
);
}
resultSet.close();
return area;
}
it somehow rounds it to 22.3234. In my app i need precise what i am storing. What is this behavior and how can i resolve this?
I use these methods when working with SQLite:
public static Double stringToDouble (String x)
{
if (x !=null)
return Double.parseDouble(x);
return null;
}
public static String doubleToString (Double y)
{
if (y != null)
return String.valueOf(y);
return null;
}
When adding to database transform the double value to string and vice-versa, and please tell me if this solution works
EDIT: The solution is in comments:
"I see you created your table with STRING fields. You can try with TEXT type, works for me."
I use a Row Set to pass query results in my selenium framework. Occasionally the data access object throws the following
java.sql.SQLException: No suitable driver found for jdbc:jtds:sqlserver://MYDatabasename:1433/DB
It uses this same driver and rowset to access and only fails occasionally. Any help would be appreciated.
RowSet:
public static RowSet GetRowSet(String SqlQuery, String[] Parameters, String DB){
CachedRowSet rs;
String ROWSET_IMPL_CLASS = "com.sun.rowset.CachedRowSetImpl";
rs = null;
try {
Class<?> c = Class.forName(ROWSET_IMPL_CLASS);
rs = (CachedRowSet) c.newInstance();
rs.setUrl(Configuration.DBConnString + DB);
rs.setUsername(Configuration.DBUser );
rs.setPassword(Configuration.DBPwd );
rs.setReadOnly(true);
rs.setCommand(SqlQuery);
for (int p=0;
p<Parameters.length;
p++)
{
rs.setString(p+1, Parameters[p]);
}
rs.execute();
Example of code:
public void examplevoid(String string, String string2)
throws Exception {
RowSet RoS = null;
RoS = Example.GetExample(string, string2);
while (RoS.next()) {
String Example = RoS.getString("Example");
selenium.click(Example)
selenium.waitForPageToLoad(setup.timeoutsetting);
}
RoS.close();
Which uses and in turn calls the rowset:
public static RowSet GetExample(String string, String string2) throws
String[] Parameters = {string, string2};
RowSet ExampleRowSet= null;
ExampleRowSet = DataAccess.GetRowSet("Some SQL HERE", Parameters, Configuration.DB);
return Example;
That seems impossible. Either the driver class is loaded, or it isn't. Once loaded, successive calls to DriverManager.getConnection() with the same JDBC URL should never give that error. What else is going on?
Edit: The only questionable thing I see is that all of your Configuration.* properties appear to be fields in a class somewhere. If some of those properties are changing values between tests, maybe your JDBC driver is causing that exception to be thrown because of a bad property value, like the Configuration.DB or Configuration.DBConnString. If it's fairly repeatable, try changing
rs.setUrl(Configuration.DBConnString + DB);
to
String url = Configuration.DBConnString + DB;
log.debug("Using JDBC URL: " + url);
rs.setUrl(url);
When the exception happens, see if the string looks different.
this is my code :
public static List populate(ResultSet rs, Class clazz) throws Exception {
ResultSetMetaData metaData = rs.getMetaData();
int colCount = metaData.getColumnCount();
List ret = new ArrayList();
Field[] fields = clazz.getDeclaredFields();
while (rs.next()) {
Object newInstance = clazz.newInstance();
for (int i = 1; i <= colCount; i++) {
try {
Object value = rs.getObject(i);
for (int j = 0; j < fields.length; j++) {
Field f = fields[j];
if (f.getName().replaceAll("_", "").equalsIgnoreCase(
metaData.getColumnName(i).replaceAll("_", ""))) {
BeanUtils.copyProperty(newInstance, f.getName(),
value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
ret.add(newInstance);
}
rs.close();
return ret;
}
and this is the method to call it :
public List getLastAddress(String terminal_id, String last_2) throws Exception {
String sql ="SELECT a.adress_reality from accounts_location_"+last_2+" AS a WHERE a.terminal_id = '"
+terminal_id+"' ORDER BY a.time_stamp DESC limit 1";
System.out.println(sql);
ResultSet rs = getDr().getSt().executeQuery(sql);
return populate(rs, Class.forName("hdt.ChineseAddressBean"));
and then :
List cn_address=sd.getLastAddress(toNomber,last_2);
System.out.println(cn_address.get(0));
but it show :
hdt.ChineseAddressBean#f0eed6
so How to get the current string from cn_address.get(0),
thanks
this is my ChineseAddressBean.java:
package hdt;
public class ChineseAddressBean {
String adress_reality = "";
public String getAdress_reality() {
return adress_reality;
}
public void setAdress_reality(String adress_reality) {
this.adress_reality = adress_reality;
}
}
updated1:
when i use this , it show error :
updated2:
this is the error :
Object address = cn_address.get(0);
ChineseAddressBean chineseaddressbean = (ChineseAddressBean)address;
System.out.println(chineseaddressbean.getAdress_reality());
The above lines is what you need to do to achieve what you want.Please let me know if its working.
Meybe you need to make method toString () in Your class instance.
Apparently you are getting a list of objects of class "ChineseAddressBean" in cn_address. Right?
Then if you do
List cn_address=sd.getLastAddress(toNomber,last_2);
System.out.println(cn_address.get(0));
It will take the first element in the list and print it. To print it, it will try to convert it to String by calling toString method of the object. So if you override toString method in class "ChineseAddressBean" and return whatever you want to print, it will do the trick
you dont have a toString() method in your bean.
public String toString() {
return adress_reality;
}
Missed in your example that you need to cast the objects retrieved from your list to the appropriate type.
So:
System.out.println((ChineseAddressBean)cn_address.get(0));
Returning List you access Object (not ChineseAddressBean). Also when you print it you call default toString() method which returns class name followed by hash code.
You have to return List<ChineseAddressBean> or cast the result to ChineseAddressBean (which you are doing wrong).
Try this one:
System.out.println(((ChineseAddressBean)(cn_address.get(0))).getAdress_reality());
You can also write toString() method for ChineseAddressBean which returns address string and then you dont have to call getAdress_reality().
cn_address.get(0) returns an object, you should convert it to a string