从jtextfield java GUI将值插入mysql表

时间:2019-02-05 16:40:18

标签: java mysql sql database user-interface

我在按下按钮时使用此代码,它应该将值插入数据库

 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);

    }

}

  

我收到此错误(java.sql.SQLSyntaxErrorException:您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以在第1行的''附近使用正确的语法)

1 个答案:

答案 0 :(得分:0)

我认为问题出在now()方法中。 尝试类似的东西:

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());