java application cannot insert null value into mysql database - java

I'm making a java program using Netbeans, I want to insert data into my "data supplier" table. I cannot post my JFrame picture as my reputation is not enough.
I've set "Kode Supplier" as PRIMARY_KEY and NOT_NULL, and allow the rest to be NULL
In the code below, telpField and hpField will show an error if I didn't type anything in it's textbox
Is it possible because it is INT type?
This is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "INSERT INTO datasupplier (`Kode Supplier`, `Nama Supplier`, `Contact Person`,"
+ " `Alamat`, `NoTelp`, `NoHP`, `Bank Account`, `A/C Info`, `A.N.`, `Keterangan`)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pst = conn.prepareStatement(sql);
//Get value from the textboxes
pst.setString(1, codeField.getText());
pst.setString(2, nameField.getText());
pst.setString(3, cpField.getText());
pst.setString(4, addressField.getText());
pst.setString(5, telpField.getText());
pst.setString(6, hpField.getText());
pst.setString(7, bankField.getText());
pst.setString(8, acField.getText());
pst.setString(9,anField.getText());
pst.setString(10, ketField.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Tabel Telah Di Update");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Data Invalid");
}
DataSupplierTable();
}
//Set JComboBox First Diplayed Item
private void setTableCombo(){
tableCombo.setSelectedItem("Data Supplier");
}
//Bind the table and databarang.datasupplier
private void DataSupplierTable(){
String sql = "SELECT * FROM datasupplier";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
supplierTable.setModel(DbUtils.resultSetToTableModel(rs));
supplierTable.isCellEditable(0,0);
}catch(Exception e){
}
}
This is my table (using MySQL Community Server Database, InnoDB)
Kode Supplier INT(30) PRIMARY_KEY NOT_NULL,
Nama Supplier CHAR(45),
Contact Person VARCHAR(20),
Alamat VARCHAR(45),
NoTelp INT(30),
NoHP INT(30),
Bank Account CHAR(30),
A/C Info VARCHAR(45),
A.N. CHAR(45),
Keterangan VARCHAR(100)

Yes, this is because your Kode Supplier, NoTelp and NoHP columns are integer columns. For integer columns, you should be using the setInt method rather than setString.
But the setInt method only accepts an primitive int for the value of the field. So the first thing you'll need to do is convert the String value of the field to int. This is done with a statement like:
int telpVal = Integer.parseInt(telpField.getText());
But this means you have to decide what to do in the following cases:
The user entered a value in the GUI field which is not an integer, like ABC, 1.2 or 123456789123456789. If that happens, then the statement I gave would throw a NumberFormatException.
You could decide to display an error message and not call the insert statement when this happens. Or you may decide to insert a NULL. Or you may decide to insert a default value like 0.
The user entered no value in the GUI field - it is an empty string. Note that there is a difference between an empty string and a null. You may decide to handle this case the same way you handle the previous one. Or you may decide to handle it separately.
Suppose you decide that:
If the user entered an illegal number, you'll show an error message and will not insert the row.
If the user did not enter a value and left the field empty, you want to insert a null.
Then you'll need to handle it like this:
String fieldName;
try {
String sql = "INSERT INTO datasupplier (`Kode Supplier`, `Nama Supplier`, `Contact Person`,"
+ " `Alamat`, `NoTelp`, `NoHP`, `Bank Account`, `A/C Info`, `A.N.`, `Keterangan`)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pst = conn.prepareStatement(sql);
//Get value from the textboxes
// Kode supplier is integer, but is not allowed to be null
// so don't handle an empty field case, just let parseInt
// throw the exception.
fieldName = "Kode Supplier";
pst.setInt(1, Integer.parseInt(codeField.getText()));
pst.setString(2, nameField.getText());
pst.setString(3, cpField.getText());
pst.setString(4, addressField.getText());
// Handle the NoTelp field - if empty, insert null. If not,
// parse the number. Handle illegal number values in catch.
fieldName = "NoTelp";
if ( telpField.getText().isEmpty() ) {
pst.setNull(5, Types.INTEGER);
} else {
pst.setInt(5, Integer.parseInt(telpField.getText());
}
// Handle the NoHP field
fieldName = "NoHP";
if ( hpField.getText().isEmpty() ) {
pst.setNull(6, Types.INTEGER);
} else {
pst.setInt(6, Integer.parseInt(hpField.getText());
}
pst.setString(7, bankField.getText());
pst.setString(8, acField.getText());
pst.setString(9,anField.getText());
pst.setString(10, ketField.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Tabel Telah Di Update");
}
catch (NumberFormatException nfe) {
// Display error to the user
JOptionPane.showMessageDialog(null, "Invalid number in field " + fieldName)
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, "Data Invalid");
}
Notes
I handled Kode Supplier differently than NoTelp and NoHP because it is not allowed to be null. If the field is empty, NumberFormatException will be thrown from parseInt and will go to the catch part.
I kept a fieldName variable which I set before trying each parseInt. If an exception is thrown, we can use it for displaying the specific field where the error occurred in the dialog box. You can do other things like keeping the JTextField that you are currently handling, and in the catch highlighting it and giving it focus.
When you use setNull, you have to pass the type of the field as the second parameter. All the types are in java.sql.Types. So remember to import java.sql.Types.
Don't use a catch (Exception e). It's too broad. In this case we expect only NumberFormatException and SQLException. If any other exception happens, especially a runtime exception, you want to know about it and see the stack trace. If you have catch (Exception e) you'll just get a dialog box that says "Data Invalid" and that is not helpful. "Catch all" is bad.

Related

Getting Syntax error in SQL query in JDBC

I am getting a syntax error, but I am mostly sure I am doing everything right. Could you take a look?
String ORDER, DROP, CAR;
String Statement = "INSERT INTO WORKORDER"
+ "(ORDER, DROPOFFDATE, COMPLETIONDATE) VALUES "
+ "( ?, ?, null);";
//JOptionPane.showMessageDialog(frame, Statement, "Daisy Imports", 3);
try {
PreparedStatement PST = connection.prepareStatement(Statement);
ORDER = JOptionPane.showInputDialog("Please assign a order number for this order");
int ORDERi = Integer.parseInt(ORDER);
DROP = JOptionPane.showInputDialog("Please Enter the date the car was dropped off (YYYY-MM-DD)");
CAR = JOptionPane.showInputDialog("Enter the VIN for the car this work order is for");
PST.setInt(1, ORDERi);
PST.setString(2, DROP);
PST.execute();
Try getting rid of the semicolon at the end of your prepared statement.
Edit: The problem was that "ORDER" is a reserved word.

inserting jtextbox value and jradiobutton value to database

I am trying to insert values from textboxes into the database but getting error com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated. I thought the problem was with radio button but when I tried to insert value in the database removing radio button and gender from the query, I am getting the same error.
I tried inserting values Name: a, Username:a ,Contact:a , radio button [male], still getting the same error.
I can not find out how I am getting this error.
create table temp (
id int IDENTITY(1,1) PRIMARY KEY,
name varchar(32) not null,
username varchar(32) not null,
contact varchar(32) not null,
gender int
);
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try
{
int gender = 0;
Connection sqlCon = DB_con.getSQLConnection();
PreparedStatement ps = sqlCon.prepareStatement(
"insert into temp (name, username, contact, gender) values ( ?, ?, ?, ?)"
);
ps.setString(1, txtName.toString());
ps.setString(2, txtUserName.toString());
ps.setString(3, txtContact.toString());
gender = (rbtnMale.isSelected()) ? 1 :2;
System.out.println("value of gender " + gender );
ps.setInt(4, gender);
int i = ps.executeUpdate();
System.out.println("records inserted: "+i);
sqlCon.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
});
It's likely that one of these:
txtName.toString()
txtUserName.toString()
txtContact.toString()
...is longer then 32 characters. Why not log them somewhere before you do the insert so you can see?
It's not clear what class these objects are from your code snippet. Is it possible that they're the default toString() method implementation of JTextField? If so, use getText(), not toString().
Change
ps.setString(1, txtName.toString());
ps.setString(2, txtUserName.toString());
ps.setString(3, txtContact.toString());
to
ps.setString(1, txtName.getText());
ps.setString(2, txtUserName.getText());
ps.setString(3, txtContact.getText());
toString is doing a debug dump of the controls, which definitely longer than 32 characters and doesn't represent the text typed into the field (or at least not in a format you want ;))

JAVA - How to avoid duplication of values in MySQL?

I'm new in MySQL. I have a problem here. I have a query of inserting a data to the database but my problem is how to avoid duplication of records.
So here are my codes:
private void btnSaveGuestActionPerformed(java.awt.event.ActionEvent evt) {
String name = nameTextField.getText();
String address = addressTextField.getText();
String nationality = nationalityTextField.getText();
String com = comNameTextField.getText();
String email = emailTextField.getText();
String contact = contactNoTextField.getText();
if( name.isEmpty() || address .isEmpty() || nationality.isEmpty() || com.isEmpty() || email.isEmpty() || contact.isEmpty() ){
JOptionPane.showMessageDialog(null, "Please input any of the following.");
}
else{
try{
String query = "INSERT INTO guestlist (Name, address, Nationality, CompanyName, email, contactNo)"
+ "VALUES ?, ?, ?, ?, ?, ?";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery("SELECT * FROM guestlist");
pst.setString(1, nameTextField.getText());
pst.setString(2, addressTextField.getText());
pst.setString(3, nationalityTextField.getText());
pst.setString(4, comNameTextField.getText());
pst.setString(5, emailTextField.getText());
pst.setString(6, contactNoTextField.getText());
pst.execute();
pst.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
Sorry for my ignorance here but I'm very new to DBMS. I hope you would answer my question. Thanks a lot and have a nice day! :)
In databases in general, you prevent duplication of records by creating unique indexes or constraints. Actually, these are basically the same thing (unique constraints are implemented using unique indexes).
So, if you wanted email to be unique, you can do:
create unique index unq_guestlist_email on guestlist(email);
Of course, you can specify multiple columns, so the combination of all the columns has to be unique.
Then, if you try to insert a record that is already there, the database will return an error. (You can ignore this error in various ways.)
in mysql you can use unique constrainst (http://www.w3schools.com/sql/sql_unique.asp).
But, if also you want validate insert data without errors in java, when you insert registers you can validate the columns that are part of your unique value, not to be repeated.

How to get integer value from JTextField of Swing?

How to get integer value from JTextField of Swing as we get string value via getText() method?
try {
String sql = "insert into employeeinfo (username,password,obtainmark) values(?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txt_username.getText());
pst.setString(2, txt_password.getText());
pst.setInt(3, txt_obtainmark.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "data inserted");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
I am not able to insert integer data type value from the JTextField, but able to insert only string or varchar type data.
You can do Integer.parseInt(string) to get Integer value.
pst.setInt(Interger.parseInt(txt_obtainmark.getText()));

Substracting value from a field in a database table taken from a textbox

I am new in java, in a java project, i want to subtract a textbox value named Quantity(q_field) from 'Available' field of database table Item_detail whenever 'sell' button is clicked and automatically update the table. I wrote some piece of code but its not working. My code is:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
if(!p_field.getText().isEmpty() && !b_field.getText().isEmpty() && !m_field.getText().isEmpty() && !sell_field.getText().isEmpty() && !c_field.getText().isEmpty()){
int a=Integer.parseInt(q_field.getText().trim());
String sql1="update Item_detail set Available=Available-'a' where P_name=? and Manuf_name =? and Model_no=?";
String sql2="insert into Sell (`S_id`,`P_name`,`Manuf_name`,`Model_no`,`Date`,`Quantity`,`S.p`,`Cost_price`) values(?,?,?,?,?,?,?,?)";
try{
pst=(PreparedStatement) con.prepareStatement(sql1);
pst.setString(1, p_field.getText());
pst.setString(2, b_field.getText());
pst.setString(3, m_field.getText());
pst.setString(4, q_field.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Product sold successfully");
update_table();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
What will be the correct sql code of 'sql1', i can not understand. Please help
sql1 shall be:
String sql1="update Item_detail
set Available=Available-?
where
P_name=?
and Manuf_name =?
and Model_no=?";
And set values to pst query to include value of variable a as follows:
pst=(PreparedStatement) con.prepareStatement(sql1);
pst.setInt(1, a);
pst.setString(2, ...
...
pst.executeUpdate();
But make sure that you have values set only for that number of palce holders in the query. Otherwise there would be a place holder count mismatch and an SQLException would be thrown.
update Item_detail set Available=Available - ? where ...
The value of a is a parameter of your query, just like the other ones. BTW, you're binding 4 different parameters to the statement, and your query only has 3 parameters (? placeholders)
Change your Update Query to this
String sql1="update Item_detail set Available=Available-? where P_name=? and Manuf_name =? and Model_no=?";
ps.setInt(1,a);

Categories

Resources