I'm getting this error when I go to update my database.Error I'm getting
This is what my database looks like Database
And here is my code:
private void updatebtnActionPerformed(java.awt.event.ActionEvent evt) {
try{
String mid = midtxt.getText();
String fname = firstnametxt.getText();
String lname = lastname.getText();
String nic = nictxt.getText();
String Address = addresstxt.getText();
String Telephone = telephonetxt.getText();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
jXDatePicker1.setFormats(dateFormat);
DateFormat sysDate = new SimpleDateFormat("yyyy/MM/dd");
String Dob = sysDate.format(jXDatePicker1.getDate());
String sql = "UPDATE `addmember` SET `FirstName`='"+fname+"',LastName`='"+lname+"',`NIC`='"+nic+"',`DOB`='"+Dob+"', `ADDRESS`='"+Address+"', `Telephone`='"+Telephone+"' WHERE MID='"+mid+"' ";
try{
Updater(sql);
JOptionPane.showMessageDialog(null, "Values Updated");
}
catch( Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
Missing backtick before LastName.
Related
I am developing a system that manages stock for a project and am trying to get a list of stock items that are close to their expiration date
This is what the table is created as:
Query_Statement.executeUpdate("CREATE TABLE STOCK_PURCHASE ( SP_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "USER_ID INTEGER,STOCK_ID INTEGER,SUPPLIER_ID INTEGER,SP_ENTRY_DATE TEXT,"
+ "SP_PURCHASE_PRICE REAL, SP_SELLBY_DATE TEXT, SP_QUANTITY REAL,"
+ "FOREIGN KEY (USER_ID) REFERENCES USER (USER_ID),"
+ "FOREIGN KEY (STOCK_ID) REFERENCES STOCK (STOCK_ID),"
+ "FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER (SUPPLIER_ID))");
This is the function to get that I use:
public ArrayList<String> GetExpiredStock(){
Connection dbConnection = null;
ResultSet list = null;
ArrayList<String> ls = new ArrayList<String>();
LocalDate currentDate = LocalDate.now();
//System.out.println(today);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");
Statement Query_Statement = dbConnection.createStatement();
Query_Statement.setQueryTimeout(10);
list = Query_Statement.executeQuery("SELECT SP_ENTRY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works
while (list.next()) {
try {
LocalDate expDate = LocalDate.parse(list.getString("SP_SELLBY_DATE"), formatter);
LocalDate monthAway = expDate.minusMonths(1);
System.out.println(currentDate);
if(currentDate.isAfter(monthAway)) {
int id = list.getInt("STOCK_ID");
ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);
ls.add(ids.getString("STOCK_NAME") + "\t\t" +
list.getString("SP_SELLBY_DATE") + getStockQuant(list.getInt("STOCK_ID"),
currentDate));
}
}catch(SQLException e) {
System.err.println(e);
continue;
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
try {
if (dbConnection != null)
dbConnection.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return ls;
}
I expect it to get the expiration date. However it keeps saying:
java.sql.SQLException: no such column: 'SP_SELLBY_DATE'
Edit:
I changed the code to look like this:
public ArrayList<String> GetExpiredStock(){
Connection dbConnection = null;
ResultSet list = null;
ArrayList<String> ls = new ArrayList<String>();
LocalDate currentDate = LocalDate.now();
//System.out.println(today);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");
Statement Query_Statement = dbConnection.createStatement();
Query_Statement.setQueryTimeout(10);
list = Query_Statement.executeQuery("SELECT SP_SELLBY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works
while (list.next()) {
try {
String da = list.getString("SP_SELLBY_DATE");
int id = list.getInt("STOCK_ID");
System.out.println("Executed on id = " + id);
LocalDate expDate = LocalDate.parse(da, formatter);
LocalDate monthAway = expDate.minusMonths(1);
System.out.println(currentDate);
if(currentDate.isAfter(monthAway)) {
ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);
ls.add(ids.getString("STOCK_NAME") + "\t\t" +
da + "\t\t"+ getStockQuant(id,
currentDate));
}
}catch(SQLException e) {
System.err.println(e);
continue;
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
try {
if (dbConnection != null)
dbConnection.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return ls;
But it still fails after the first iteration
Your SQL query doesn't have the required column, add it :
SELECT SP_ENTRY_DATE, STOCK_ID, SP_SELLBY_DATE FROM STOCK_PURCHASE
I believe you query it list.getString("SP_SELLBY_DATE") twice in your loop, that should be root cause. Instead, you should use a variable when you get it to avoid to call it again as cursor has changed.
I need to insert Date to my database, so I convert date received from user to SQL Date and then try to insert date to database. But in process SQL date object is evaluate to integer and thus insertion fails .
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String enrollNo = request.getParameter("enroll_no");
String name = request.getParameter("name");
String age = request.getParameter("age");
java.util.Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("dob"));
} catch (ParseException e) {
e.printStackTrace();
}
Date SqlDate = new Date(date.getTime());
process(enrollNo, name, age, SqlDate);
response.sendRedirect("listing.jsp");
}
void process(String enrollNo, String name, String age, Date date) {
DatabaseOperations db = new DatabaseOperations("java", "root", "", "jsp");
db.insert(enrollNo, name, age, date);
}
Insert method of DatabaseOperations class
public int insert(Object...objects) {
int rowsAffected = 0;
String query = "INSERT INTO " + tableName + " VALUES (";
for(int i=0; i<objects.length-1; i++)
query += "'" + objects[i] + "',";
query += objects[objects.length-1] + ")";
try {
rowsAffected = statement.executeUpdate(query);
} catch (SQLException e) {
printSQLExceptions(e);
}
return rowsAffected;
}
While inserting date 11/02/2000 following error shows up
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '1987' for column 'Dob' at row 1
I have 2 Frames let's name them "Request" and "Confirm". Now when clicking a Button in "Request" the Frame "Confirm" is called. And when clicking "yes" a SQL Statement should be executed. The thing is that the SQL Statement is in class "Request". The Class "Confirm" should be called from other Frames too, so I don't want to make an Action Listener on the Button "yes" in "Confirm". I what to get a boolen by clicking the "yes" Button. If its true the statement in 'Request" should be executed.
How I can do this?
ReqBnt.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
if (arg0.getSource() == ReqBnt) {
String VendN = txtVendN.getText();
String VendSN = txtVendSN.getText();
String Ad = txtAd.getText();
String Ads = txtAds.getText();
String City = txtCity.getText();
String Zip = txtZip.getText();
String UID = txtUID.getText();
String Reg = txtReg.getText();
String Rep = txtRep.getText();
String Tel = txtTel.getText();
String Fax = txtFax.getText();
String Mail = txtMail.getText();
String Iban = txtIban.getText();
String Bic = txtBic.getText();
String BInst = txtBInst.getText();
String VendInfo = txtVendInfo.getText();
String Flag = "Y";
String PT = comboPT.getSelectedItem().toString();
String Ctry = comboCtry.getSelectedItem().toString();
try{
try {
String sqlx = "SELECT `Abbreviation 2`, `Country English` From `database`.`country_master` " +
"WHERE `Country English` = '" + Ctry + "'";
PreparedStatement pstx = conn.prepareStatement(sqlx);
ResultSet rs = pstx.executeQuery();
while (rs.next()){
partCode = rs.getString("Abbreviation 2");
}}catch (Exception ex) {
System.out.println("Abbreviation Not Found");
}
String sqlFind = "Select max(substring(`Vendor Code`, 3)) From `database`.`vendor_master`";
try {
PreparedStatement pstFind = conn.prepareStatement(sqlFind);
ResultSet rs = pstFind.executeQuery();
while (rs.next()){
partNo = rs.getInt("Vendor Code")+1;
}}catch (Exception ex) {
partNo = 10001;
}
String VendC = partCode+partNo;
try {
String sqlx = "SELECT `Abbreviation Use`, `Country English` From `database`.`country_master` " +
"WHERE `Country English` = '" + Ctry + "'";
PreparedStatement pstx = conn.prepareStatement(sqlx);
ResultSet rs = pstx.executeQuery();
while (rs.next()){
CtryC = rs.getString("Abbreviation Use");
}}catch (Exception ex) {
System.out.println("Abbreviation Not Found");
}
Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
//if
// 1.step: check if there are null values
// 2.step: if there are no null values -> call frame "Confirm"
// 3.step: if Confirm = true -> execute statement
// if Confitm = fals -> do nothing
try {
String sql = "INSERT INTO `database`.`vendor_master`(`Vendor Code`,`Vendor Full Name`,`Vendor Short Name`,"+
"`Address`,`Address Suffix`,`ZIP Code`,`City`,`Country`,`Country Code`,`UID No`,`Registration No`,"+
"`Payment Term`,`Creation Date`,`IBAN`,`BIC`,`Banking Institution`,`Representive`,`Email Address`,"+
"`Telefon No`,`Fax`,`Vendor Information`,`Active Flag`) "+
"Values('"+VendC+"','"+VendN+"','"+VendSN+"','"+Ad+"','"+Ads+"','"+Zip+"','"+City+"','"+Ctry+"','"+CtryC+"','"+
UID+"','"+Reg+"','"+PT+"','"+dateNow+"','"+Iban+"','"+Bic+"','"+BInst+"','"+Rep+"','"+Mail+"','"+Tel+"','"+
Fax+"','"+VendInfo+"','"+Flag+"')";
PreparedStatement pstExecute = conn.prepareStatement(sql);
pstExecute.execute();
System.out.println("Vendor Registered");
}catch (Exception ex) {
System.out.println("Please insert required Fields!");
}
///end if
}catch (Exception ex) {
System.out.println("Error: "+ex);
}
}
}
});
Try using a JDialog instead:
int dialogResult = JOptionPane.showConfirmDialog (
null,
"Are you sure you want to do that?",
"Warning",
JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
//Do a thing here
}
You can Take a look at the dialog here:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
You can even extend JDialog instead if you want more functionality.
I am trying to insert date into mysql. The field is of date type
but when I select a date from datepicker and insert it into database,it takes a random date..not getting where the problem is..
the code is as follow:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date d = null;
Date parsed = null;
try {
parsed = format.parse(request.getParameter("dt"));
System.out.println(parsed);
if (parsed != null) {
d = new java.sql.Date(parsed.getTime()); //parsed.getTime(
System.out.println(d);
} else {
d = new java.sql.Date(new Date().getTime());
}
} catch (ParseException e1) {
e1.printStackTrace();
}
String nature = request.getParameter("call_nature");
String name = request.getParameter("c_name");
String cat = request.getParameter("call").toString();
String num = request.getParameter("phone_no");
String street = request.getParameter("streetno").toString();
String rbut = request.getParameter("c_room");
String val = request.getParameter("hidd");
String zone = request.getParameter("combo1").toString();
String div = request.getParameter("combo2");
String hrs = request.getParameter("hr1");
String mns = request.getParameter("mn1");
String am = request.getParameter("ap1");
String occup = request.getParameter("occu");
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionurl = "jdbc:mysql://localhost:3306/fms";
String user = "root";
String pass = "root";
Connection con = DriverManager.getConnection(connectionurl, user, pass);
String sql = "insert into fire_reg values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prst = con.prepareStatement(sql);
prst.setString(1, nature);
prst.setString(2, cat);
prst.setString(3, name);
prst.setString(4, num);
prst.setString(5, val);
prst.setString(6, street);
prst.setDate(7, d);
prst.setString(8, rbut);
prst.setString(9, zone);
prst.setString(10, div);
prst.setString(11, hrs);
prst.setString(12, mns);
prst.setString(13, am);
prst.setString(14, occup);
if (prst.executeUpdate() == 1) {
request.setAttribute("loc", street);
//System.out.println(street);
request.setAttribute("phone", num);
request.setAttribute("calltypee", cat);
request.setAttribute("zonee", zone);
RequestDispatcher rd = request.getRequestDispatcher("FMS14_DelhiRegMap.jsp");
rd.forward(request, response);
}
} catch (Exception e) {
System.out.println(e);
}
the error occur near the parsing of proj_close_date.( java.text.ParseException: Unparseable date: "09/09/2010" )
i am reading project_close_date value from database which is in string format. i want convert it in to date format to find that, is proj_close_date present between from_date and to_date
public ArrayList viewAllCustProj1(String frm_date,String to_date,String cust,String proj)
{
ArrayList list= new ArrayList();
try
{
String strCust="";
String strproj="";
if(!cust.equalsIgnoreCase("ALL") && !cust.equals(null))
{
strCust="and customer_code='"+cust+"'";
}
if(!proj.equalsIgnoreCase("ALL") && !proj.equals(null))
{
strproj="and project_code='"+proj+"'";
}
if(cust.equalsIgnoreCase("ALL") && !proj.equalsIgnoreCase("ALL"))
{
}
else
{
stmt=conn.prepareStatement("select customer_code from mst_customer where visible=1 "+strCust+" and category='EU' and multiple_project=0");
rs=stmt.executeQuery();
while(rs.next())
{
reportBean bean=new reportBean();
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code("");
list.add(bean);
}
rs.close();
stmt.close();
}
System.out.println(" select customer_code,project_code,proj_close_date,added_on from mst_project where visible=1 "+strCust+" "+strproj+"");
stmt=conn.prepareStatement("select customer_code,project_code,proj_close_date,added_on from mst_project where visible=1 "+strCust+" "+strproj+"");
rs=stmt.executeQuery();
while(rs.next())
{
reportBean bean=new reportBean();
String proj_close_date=rs.getString(3);
String added_on=rs.getString(4);
DateFormat myDateFormat = new SimpleDateFormat("MM-dd-yyyy");
DateFormat myDateFormat1= new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date myDate1 = null;
Date myDate2 = null;
Date myDate3 = null;
Date myDate4 = null;
Date myDate5 = null;
try
{
if(proj_close_date==null || proj_close_date.trim().equals("") || proj_close_date=="NULL")
{
System.out.println("\n ****** In IF Loop ");
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
System.out.println("\n ****** In Else Loop ");
myDate1 = myDateFormat.parse(proj_close_date);
myDate2 = myDateFormat.parse(frm_date);
myDate3 = myDateFormat.parse(to_date);
myDate5 = myDateFormat1.parse(added_on);
//myDate4 = myDateFormat.format(myDate5);
System.out.println("Project Code ---->"+rs.getString(2));
System.out.println("Proj_close_date ------>"+myDate1);
System.out.println("From Date ---->"+myDate2);
System.out.println("to Date ---->"+myDate3);
//System.out.println("Added_on --->"+myDate4);
System.out.println("Added_on 1 ie Date 5 ---->"+myDate5);
if(myDate1.after(myDate2) && myDate1.before(myDate3)) // means --> if(proj_close_date.after(frm_date) && proj_close_date.before(to_date))
{
if(myDate1.after(myDate4)) // means --> if(proj_close_date.after(added_on))
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
}//if
}//else
}//try
catch (ParseException e)
{
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
rs.close();
stmt.close();
}
catch(SQLException sex)
{
sex.printStackTrace();
}
finally
{
closeConnection();
}
return list;
}
Change this line
DateFormat myDateFormat = new SimpleDateFormat("MM-dd-yyyy");
to this:
DateFormat myDateFormat = new SimpleDateFormat("MM/dd/yyyy");
However, it's quite unclear why you get all the values as strings, perhaps you should consider dedicated ResultSet methods such as getDate or getTimeStamp.
As another side remark I'd like to mention that building SQL queries by concatenation should be avoided -- you should generate queries with ? placeholders, and then set the parameters on your PreparedStatement.