从netbeans向数据库mysql插入数据

时间:2015-05-13 16:59:51

标签: java mysql swing netbeans insert

我已经在我的注册表格中堆叠了。我不知道错误在哪里 这是我的联系:

package login;

import java.sql.*;
import java.text.SimpleDateFormat;
import javax.swing.*;

public class register extends javax.swing.JFrame {

public PreparedStatement pst;
public Connection cn;
public Statement st;

public register() {
    initComponents();
    try {
        Class.forName("com.mysql.jdbc.Driver");
        cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/tugas?zeroDateTimeBehavior=convertToNull","root","");
        st=cn.createStatement();
        JOptionPane.showMessageDialog(null, "Connected");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Not Connected");
    }
}

我有按钮点击保存或插入数据库,但它失败或错误:

private void btnsumbitActionPerformed(java.awt.event.ActionEvent evt) {                                          
    try {
        String sql = "INSERT INTO `pasien`(`Username`, `Password`, `Nama_Depan`, "
                + "`Nama_Belakang`, `Tanggal_Lahir`, `Alamat`, `No_Telp`, `Jenis_Kelamin`) "
                + "VALUES (?,?,?,?,?,?,?,?)";
        pst = cn.prepareStatement(sql);
        pst.setString(1, user.getText());
        pst.setString(2, String.valueOf(pass.getPassword()));
        pst.setString(3, nmdepan.getText());
        pst.setString(4, nmblkg.getText());
        pst.setString(5, ((JTextField)txt_Date.getDateEditor().getUiComponent()).getText());
        pst.setString(6, alamat.getText());
        pst.setString(7, telp.getText());
        pst.setString(8, kelamin.getSelectedItem().toString());
        pst.execute();
        JOptionPane.showMessageDialog(null, "Register Berhasil");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Terjadi Kesalahan");
    }
}               

此代码可以执行,但无法插入数据库或失败。

1 个答案:

答案 0 :(得分:0)

向我们提供更多信息:

  • sql table variables
  • 输出错误

查看变量的类型 或使用此代码来更好地捕捉错误

try {
     //You code there
}
catch (SQLException e) {
  while (e != null) {
      System.out.println("\n Message: " + e.getMessage());
      System.out.println("\n SQLState: " + e.getSQLState());
      System.out.println("\n ErrorCode: " + e.getErrorCode());
      e = e.getNextException();
  }
}