简体   繁体   中英

insert values into mysql table from jtextfield java GUI

I use this code when i press button , it should insert values into database

 code  else if(a.getSource()==New){

          try{
            if(Cpphone.getText().equals("")||Dnname.getText().equals("")||array.equals("")|| totalcost==0)
               {
                  JOptionPane.showMessageDialog(this,
                 "Please insert all information before submitting.", "", JOptionPane.INFORMATION_MESSAGE);
                }
            else{          
            Connection mycon= DriverManager.getConnection("jdbc:mysql://localhost:3306/projectofpharmacy","root","sherouk");
            Statement mystat=mycon.createStatement();

            mystat.executeUpdate("insert into pharmacy_orders (patintphone,doctorName,OrderdateTime,totalCost) values ('"+Cpphone.getText()+"','"+Dnname.getText()+"',now(),'"+totalcost+"'");
           JOptionPane.showMessageDialog(this,
                 "the process is done successfuly.", "", JOptionPane.INFORMATION_MESSAGE);

           array=null;
           totalcost=0;

        }   
        }
        catch(Exception e){
            System.out.println(e);

             JOptionPane.showMessageDialog(this,
                 e.toString(), "", JOptionPane.INFORMATION_MESSAGE);

    }

}

I get this error (java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1)

I think the problem is in now() method. Try something like:

private static java.sql.Date getCurrentDate() {
    java.util.Date today = new java.util.Date();
    return new java.sql.Date(today.getTime());
}

String insertTableSQL = "INSERT INTO DBUSER"
    + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
    + "(?,?,?,?)";
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setDate(4, getCurrentDate());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM