无法将条目放入mysql数据库中

时间:2014-04-17 16:48:10

标签: java mysql sql swing

private void B_save_pActionPerformed(java.awt.event.ActionEvent evt)      {                                         

    try{

        String db = "jdbc:mysql://localhost/ar";
        Connection con = DriverManager.getConnection(db, "rehan", "1234");
        PreparedStatement ps;
        String sql = "INSERT INTO purchase (item_type, md_by, model, selling_price, purchase_price, purchase_date, item_image, vouch_no, vouch_date) VALUES ('?', '?', '?', ?, ?, '?', ?, ?, '?');" ;
        ps = con.prepareStatement(sql);


            ps.setString(1 , txt_itype_p.getText());
            ps.setString(2, txt_md_by_p.getText());
            ps.setString(3, txt_model_p.getText());
            ps.setString(4, txt_s_price_p.getText());
            ps.setString(5 , txt_p_price.getText());
            ps.setString(6, null);
            ps.setString(7, null);
            ps.setString(8, txt_vouch_p.getText());
            ps.setString(9 , null);

            ps.execute();



    }
    catch(SQLException ex){
        JOptionPane.showMessageDialog(null, ex);

}   
    DefaultTableModel tblModel = (DefaultTableModel) Table_p.getModel();
    if(!txt_itype_p.getText().trim().equals(""))     {
    tblModel.addRow(new Object[]{tbl_sr, txt_itype_p.getText(),txt_model_p.getText(),txt_md_by_p.getText(),txt_date_p.getText(),txt_p_qty.getText(),txt_p_price.getText(),txt_s_price_p.getText()});   
    txt_itype_p.setText(null);
    txt_ipath.setText(null);
    txt_itype_p.setText(null);
    txt_md_by_p.setText(null);
    txt_model_p.setText(null);
    txt_p_date.setText(sdf.format(date));
    txt_p_price.setText(null);
    txt_p_qty.setText(null);
    txt_s_price_p.setText(null);

    }
    tbl_sr = tbl_sr +1;    
    saved = true;/*If someone accidently click the close button, system will
    confirm while getting the value of this bolean variable*/
}                                        

这是我的保存按钮的代码,该按钮应该在JFrame中显示JTable上的条目,并且还将条目保存到mysql数据库中以便购买'表,但问题是它显示JTable上的条目但不保存在数据库中。我有相同的代码来创建新用户,在数据库的登录表中保存用户名,密码和帐户类型,并且该代码工作正常。我有一种感觉,这个问题是由于一些数据类型问题,但我没有得到证实。 我正在使用Netbeans和mysql数据库。我试图发送' null'到目前为止和图像数据类型,但仍然无法正常工作。 有人请帮助我。

1 个答案:

答案 0 :(得分:1)

这一行存在问题:

String sql = "INSERT INTO purchase (item_type, md_by, model, selling_price, purchase_price, purchase_date, item_image, vouch_no, vouch_date) VALUES ('?', '?', '?', ?, ?, '?', ?, ?, '?');" ;

问题是由单引号包围的五个?。 JDBC不会将这些识别为占位符,并假设您要将仅包含?字符的字符串插入item_typemd_bymodelpurchase_datevouch_date列。

修复方法是删除?标记周围的所有单引号:

String sql = "INSERT INTO purchase (item_type, md_by, model, selling_price, purchase_price, purchase_date, item_image, vouch_no, vouch_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);" ;