how to insert date in mysql using jsp? - java

this is my edited code...
java.sql.Timestamp sqlNow = new java.sql.Timestamp(new java.util.Date().getTime());
stmt = con.createStatement();
//stmt.executeUpdate("INSERT INTO cregn values('"+appno+"','"+usname+"','"+upwd +"','"+fname+"','"+mname+"','"+lname+"','"+dob+"','"+gend+"','"+faname+"','"+saddr+"','"+caddr+"','"+staddr +"','"+pin+"','"+cno+"','"+email+"','"+occ+"','"+secques+"','"+answer+"','Processing','"+sqlNow+"')");
pst = con.prepareStatement("INSERT INTO cregn (aplno, username, pwd, firstname,middlename,lastname, dob,gender, fathername, street,city,state, pincode, phone, email,occupation,secques,answer,dor) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pst.setInt(1, appno);
pst.setString(2, usname);
pst.setString(3, upwd);
pst.setString(4, fname);
pst.setString(5, mname);
pst.setString(6, lname);
pst.setString(7, dob);
pst.setString(8, gend);
pst.setString(9, faname);
pst.setString(10, saddr);
pst.setString(11, caddr);
pst.setString(12, staddr);
pst.setString(13, pin);
pst.setString(14, cno);
pst.setString(15, email);
pst.setString(16, occ);
// pst.setString(17,ph);
pst.setString(17, secques);
pst.setString(18, answer);
pst.setTimestamp(19, sqlNow);
pst.executeUpdate();
out.println("Registration Successful for application " + appno);
} catch (Exception ee) {
out.println("Invalid Data! All fields are mandatory..." + ee.getMessage());
}
%>
after executing this code error displayed "Invalid Data! All fields are mandatory..data truncation"

You are not executing the statement.
You need to call executeUpdate

You have to call execute or executeUpdate on pst in order to actually do the work. E.g., at the end:
pst.executeUpdate();
All that the code you've shown does is prepare the statement for execution, it doesn't execute it. This is one of the main differences between PreparedStatement and Statement. In Statement, you pass the SQL to execute directly into executeUpdate (as seen in your commented-out line using stmt). With a PreparedStatement, you supply the SQL with ? as you've done, set those parameters, and then call executeUpdate (or execute), which you haven't done.

There is no executeUpdate() being called on pst.

use pst.executeUpdate(); to execute the query and make sure that in transaction use setAutoCommit(true) has to be called.

Related

Not saving into MySQL database in Java

I created a form to insert drug information to the db.
Only ItemID, ItemName and Expiry date is required.
User can add other details if want.
My code for above functionality;
private void Save_btnActionPerformed(java.awt.event.ActionEvent evt) {
try {
String id = itemid_txt.getText();
String name = itemname_txt.getText();
String rec=reclevel_txt.getText();
String qty=qty_txt.getText();
String wp =wprice_txt.getText();
String sp =sprice_txt.getText();
Date expp =expday_chooser.getDate();
String dess = des_txtarea.getText();
String date = ((JTextField)dayChooser.getDateEditor().getUiComponent()).getText();
String exp = ((JTextField)expday_chooser.getDateEditor().getUiComponent()).getText();
String des = des_txtarea.getText();
if(id==null && name==null && exp==null){
JOptionPane.showMessageDialog(null, "Fill required fields(Item ID ,Item Name ,Exp Date) and Try again...");
}else if(wp!=null && sp!=null && rec!=null && qty!=null && exp==null){
String sql = "Insert into druginfo (ItemID,ItemName,AddedDate,RecorderLevel,InStock,WSPrice,CostPrice,ExpDate,Description)values (?,?,?,?,?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, id);
pst.setString(2, name);
pst.setString(3, date);
pst.setString(4, dess);
pst.setString(5, qty);
pst.setString(6, wp);
pst.setString(7, sp);
pst.setString(8, exp);
pst.setString(9, des);
}else{
pst.setString(1, id);
pst.setString(2, name);
pst.setString(3, date);
pst.setString(4, null);
pst.setString(5, null);
pst.setString(6, null);
pst.setString(7, null);
pst.setString(8, null);
pst.setString(9, des);
}
pst.execute();
JOptionPane.showMessageDialog(null, "New Item Data Saved...");
itemid_txt.setText(null);
itemname_txt.setText(null);
reclevel_txt.setText(null);
qty_txt.setText(null);
wprice_txt.setText(null);
sprice_txt.setText(null);
expday_chooser.setDate(null);
des_txtarea.setText(null);
} catch (SQLException ex) {
Logger.getLogger(InventoryManagementenew.class.getName()).log(Level.SEVERE, null, ex);
}
}
But not adding to the database when only required fields given and all fields are are given. Code throws java.lang.NullPointerException .
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.bit.project.InventoryManagementenew.Save_btnActionPerformed(InventoryManagementenew.java:468)
at com.bit.project.InventoryManagementenew.access$500(InventoryManagementenew.java:27)
at com.bit.project.InventoryManagementenew$6.actionPerformed(InventoryManagementenew.java:366)
line 468 is pst.setString(1, id);.
Help me to correct this.
You only initialize the PreparedStatement in the else if clause. The else part has neither the sql string nor the prepared statement.
State pst=conn.prepareStatement(sql); before your if-else conditions currently it will only be initialized in first else if part otherwise pst will be null in subsequent else-if and else block.
Your preparedStatement object is referring to null as it is only initialized in if block of if-else-if construct.
To solve the problem either initialize the preparedStatement outside if-else-if block or initialize it in each block if, elseif and else.
One thing more you are not closing preparedStatement in your code this could lead to memory leak and will cause out of memory or too many connections to DB at higher rate of transactions in future.

Inserting in database using java1001

I always get this error every time i try to save or execute the query.
I can't work it out,maybe alittle advice will help.
java.sql.SQLException: can not issue data manipulation statements with
executeQuery()
here is my code for inserting into my database.
Connection conn=null; ResultSet rs = null,rs1=null; PreparedStatement
pst = null,pst1=null;
DefaultTableModel model= (DefaultTableModel)tbl_stud.getModel();
try{
String sql="INSERT INTO students (id_num,fname,mname,lname,course,gender,year,username,password) VALUES(?,?,?,?,?,?,?,?,?);";
model.setNumRows(0);
pst=conn.prepareStatement(sql);
String id=txt_idnum.getText();
pst.setString(1,id);
String f=txt_fname.getText();
pst.setString(2, f);
String m=txt_mname.getText();
pst.setString(3, m);
String l=txt_lname.getText();
pst.setString(4, l);
String crs=cmb_course.getSelectedItem().toString();
pst.setString(5, crs);
String gen=cmb_gender.getSelectedItem().toString();
pst.setString(6, gen);
String year = cmb_year.getSelectedItem().toString();
pst.setString(7, year);
String uname=txt_username.getText();
pst.setString(8, uname);
String pass=txt_password.getText();
pst.setString(9, pass);
pst.executeQuery(sql);
JOptionPane.showMessageDialog(null, "Saved!","",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e,"",JOptionPane.ERROR_MESSAGE);
}
you need to use pst.executeUpdate rather then pst.executeQuery
The exception message says it all:
can not issue data manipulation statements with executeQuery()
Instead, you should use executeUpdate(). Additionally, if you've already prepared the statement, you should use the execute variants that do not receive a String argument. Those are inherited from Statement and should not be used with PreparedStatements (and yes, this does go a long way towards showing that JDBC is a terrible API).
pst.executeUpdate();
As an additional sidenote, you should drop the semicolon (;) and the end of your insert statement. Depending on the exact driver and RDBMS you're using it may either be redundant or just plain out wrong.

Number of query values and destination fields are not the same in Java

I have a prepardStatement which should perform an insert to MS Access
Below is the SQL
INSERT INTO DonorDetails (Title,FirstName,LastName,[IC NUMBER],[OLD IC NUMBER],Gender,DOB,COUNTRY,Race,[Address 1],[Address 2],[Address 3],[Address 4],City,State,Postcode,[TEL HSE],[TEL HP],[TEL OFF],[Fax Number],Email,Language,[Donation Amount],Frequency,Bank,MODE,[CHQ/MO/PO],[CREDIT CARD],[NAME OF CARD HOLDER],Expiry,[ISSUING BANK],[ACCOUNT NUMBER],CAMPAIGN,[SERIAL NO],[EVENT CODE],[AGENT ID],Channel,[SOURCE CODE],[SIGNUP DATE],Remarks, [Date Processed])values (?,?,?.?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
During insert I get the following error
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
This is how I execute my code which I believe the number of fields / columns is 41
Connection conn = Connect.ConnectDB();
System.out.println(sql);
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, salutation);
pst.setString(2, txtFirstName.getText());
pst.setString(3, txtLastName.getText());
pst.setString(4, newID);
pst.setString(5, oldID);
pst.setString(6, String.valueOf(cbGender.getSelectedItem()));
pst.setString(7, dobDate);
pst.setString(8, String.valueOf(cbNationality.getSelectedItem()));
pst.setString(9, race);
pst.setString(10, txtAddress.getText());
pst.setString(11, txtAddress2.getText());
pst.setString(12, txtAddress3.getText());
pst.setString(13, txtAddress4.getText());
pst.setString(14, txtCity.getText());
pst.setString(15, String.valueOf(cbState.getSelectedItem()));
pst.setString(16, txtPostCode.getText());
pst.setString(17, txtHomePhone.getText());
pst.setString(18, txtMobilePhone.getText());
pst.setString(19, txtOfficePhone.getText());
pst.setString(20, txtFax.getText());
pst.setString(21, txtEmail.getText());
pst.setString(22, txtLanguage.getText());
pst.setInt(23, amount);
pst.setString(24, frequency);
pst.setString(25, bankName);
pst.setString(26, mode);
pst.setString(27, prependNo + txtRefNo.getText());
pst.setString(28, cardNumber);
pst.setString(29, cardName);
pst.setString(30, cardExpiry);
pst.setString(31, issuingBank);
pst.setString(32, accountNumber);
pst.setString(33, String.valueOf(cbCampaign.getSelectedItem()));
pst.setString(34, lblSerialCode.getText()
+ txtSerialNumber.getText());
pst.setString(35, txtTeritoryCode.getText());
pst.setString(36, txtAgentID.getText());
pst.setString(37, String.valueOf(cbChannel.getSelectedItem()));
pst.setString(38, "OPTIMO");
pst.setString(39, df.format(signUpDate.getDate()));
pst.setString(40, textField.getText());
pst.setString(41, processedDate);
pst.execute();
I am unable to find what is wrong with the above code.

Save data to mysql database in java

hello everyone i need your help.. i'm trying to save data to mysql database in java using netbeans IDE my source code doesn't want to run"it gives me an error that says"Java.lang.NullPointerExcepion
here's my source code..
try{
String sql = "Insert into clients(username,Id_number,surname,fullname,age,diagnose) values(?,?,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txt_surname.getText());
pst.setString(2, txt_fullname.getText());
pst.setString(3, txt_age.getText());
pst.setString(4, txt_diagnose.getText());
pst.setString(5, txt_ID.getText());
pst.setString(6, txtusername.getText());
//pst.setString(7, txt_password.getText());
pst.execute();
JOptionPane.showMessageDialog(null,"Saved");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
This code is clear and ok. the only possible var causing trouble is con. So try to add a sysout print statement before all con == null and look if it is true, then check whats missing on the connection setup

sql server index out of range error

i have this error . The index 2 is out of range. on pst.setString(2, textField.getText();
how can i deal with it.
this is my code
try{
String sql="update inventory set Name=?,Category=?,Brand=?,Price=?,ExDate=?,Tags=?,Quantity=?,Barcode=? where Id=?";
pst.setString(2, textField.getText());
pst.setString(3, textField_1.getText());
pst.setString(4, textField_2.getText());
pst.setString(5, textField_3.getText());
pst.setString(6, textField_4.getText());
pst.setString(7, textField_5.getText());
pst.setString(8, textField_9.getText());
pst.setString(9, textField_6.getText());
pst.setString(1, textField_8.getText());
pst=con.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Updating Item Successful","Updated",JOptionPane.PLAIN_MESSAGE);
new server().setVisible(true);
setVisible(false);
} catch(Exception e1){e1.printStackTrace();}
Based on the documentation, Couple of things to notice here.
your sql contains name att index 1. So when you try to update this column you should use the same index. something like this:
pst.setString(1, textField.getText());
You are always invoking setString methods. Although it looks like some of the columns might be of type int or else. for example your 'id' column should be set with this:
pst.setInt(9, Integer.parseInt(textField_8.getText())); (notice that I have changed the index as well.)
And as I mentioned in my comment earlier, you should move your pst=con.prepareStatement(sql) to the top. (right after your string declaration.)
A prepared statement should be created before being used to set the variables. As the commenter said you need to move the prepared statement creation before setting variables to it.
Refactor your code like this:
try{
String sql="update inventory set Name=?,Category=?,Brand=?,Price=?,ExDate=?,Tags=?,Quantity=?,Barcode=? where Id=?";
pst=con.prepareStatement(sql);
pst.setString(2, textField.getText());
pst.setString(3, textField_1.getText());
pst.setString(4, textField_2.getText());
pst.setString(5, textField_3.getText());
pst.setString(6, textField_4.getText());
pst.setString(7, textField_5.getText());
pst.setString(8, textField_9.getText());
pst.setString(9, textField_6.getText());
pst.setString(1, textField_8.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Updating Item Successful","Updated",JOptionPane.PLAIN_MESSAGE);
new server().setVisible(true);
setVisible(false);
}
catch(Exception e1)
{
e1.printStackTrace();
}
finally
{
pst.close();
}

Categories