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 ;))
Related
I have the following code:
public void updateAccount(String username, String name, String address, String aboutMe,
String id) {
String sql = "update Account set username = ?, \n"
+ " [Full_Name] = ?,\n"
+ " [Address] = ?,\n"
+ " [about_me] = ?\n"
+ " where id = ?";
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, name);
ps.setString(3, address);
ps.setString(4, aboutMe);
ps.setString(5, id);
ps.executeUpdate();
} catch (Exception ex) {
Logger.getLogger(AccountDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
But when I change something like username, fullname in my web, they are still not updated and show the following error:
Severe: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into
column 'username', table 'FERA_ONL_LEARNING.dbo.Account'; column does not allow nulls. UPDATE
fails. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:328)
at dao.AccountDao.updateAccount(AccountDao.java:142)
at controller.UserProfileController.doPost(UserProfileController.java:91)
I'm sure I changed their values and it can't be NULL.
How to fix this error?
Have you tried printing the result of your dynamic query? You could add a system.out.println(sql) before ps.executeUpdate(), to verify that your variables are being assigned the value correctly.
I estimate by how the sql is concatenated that it is not taking the positions correctly and by default the setString returns NULL.
My app allows users to create an account (stored in database) and place orders.
When a client registers himself, I want to generate a primary key named CLIENT_CODE to identify him, starting from x value and increment it with y value. (I'm using oracle 11g atm)
I've tried this so far:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String fname = jTextField9.getText();
String lname = jTextField10.getText();
String city = jTextField11.getText();
String street = jTextField13.getText();
String number = jTextField14.getText();
String userClient = jTextField15.getText();
String pass1 = String.valueOf(jPasswordField5.getPassword());
String pass2 = String.valueOf(jPasswordField6.getPassword());
if(verifyFields()){
if(!checkUsername(userClient)){
OraclePreparedStatement ps;
OracleResultSet rs;
String registerClient = "insert into CLIENT (FNAME_CL, LNAME, CITY, STREET, NUMBER, MONEY, CLIENT_CODE, USER_CLIENT, PASS) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
ps = (OraclePreparedStatement) JavaConnectDb.ConnectDb().prepareStatement(registerClient);
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, city);
ps.setString(4, street);
ps.setString(5, number);
ps.setDouble(6, 0.0);
ps.setInt(7, ???); <--- here should be the generated primary key
ps.setString(8, userClient);
ps.setString(9, pass1);
if(ps.executeUpdate() != 0){
JOptionPane.showMessageDialog(null, "Account created!");
} else{
JOptionPane.showMessageDialog(null, "Error: Check your info");
}
} catch (SQLException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Don't do it in Java; handle the primary key value creation in the database using a sequence:
CREATE SEQUENCE CLIENT__CLIENT_CODE__SEQ
START WITH 1
INCREMENT BY 1
Then just use your sequence in the INSERT statement and use the RETURNING clause to get the generated value as an OUT parameter of your prepared statement.
insert into CLIENT (
FNAME_CL,
LNAME,
CITY,
STREET,
NUMBER,
MONEY,
CLIENT_CODE,
USER_CLIENT,
PASS
) values (
?,
?,
?,
?,
?,
?,
CLIENT__CLIENT_CODE__SEQ.NEXTVAL,
?,
?
) RETURNING CLIENT_CODE INTO ?
If you were using Oracle 12c then you could use GENERATED AS IDENTITY in the table's CREATE DDL statement to generate the values without creating a separate sequence.
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.
So I am making a registration page and when I enter all the fields and click signup to submit, enterNewUser(,,,) is called and the fields userId, username,password and role are inserted into the table User. I confirm this by running select * from user; into MYSQL workbench.
Then enterUsername(,,,) is called and I get this error:
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 '(3,'Barry','Allen')' at line 1
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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
'(3,'Barry','Allen')' at line 1
public static int enterNewUser(String username,String password, String role){
//int userId = -1;
int ID = 0;
//int ID=-1;
try{
if(checkUserNameAvailable(username)==true){
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost/log", "root", "root");
String q0 = "Select userId from user ORDER BY userId DESC LIMIT 1"; //get ID of last
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(q0);
if(rs.next()){
ID = rs.getInt("userId");
ID++;
}
else
ID=1; // Empty Table, so start with ID 1
rs.close();
st.close();
String q1="insert into user values(?,?,?)";
PreparedStatement ps = cn.prepareStatement(q1);
//ps.setInt(1,ID);
ps.setString(1,username);
ps.setString(2,password);
ps.setString(3,role);
ps.executeUpdate();
ps.close();
}
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
DB_close();
//if(userId!=-1)
// return userId;
return -1;
}
public static boolean enterUsername(int userId, String firstname, String lastname){
try{
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost/log", "root", "root");
//String q1="INSERT INTO user_profile values(?,?,?)";
String q1 = "INSERT into user_profile (userId, firstname, lastname) VALUES (?,?,?)";
PreparedStatement ps = cn.prepareStatement(q1);
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
ps.executeUpdate();
ps.close();
return true;
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
DB_close();
return false;
}
Here is my database structure.
Edit: found the issue, database was not structured properly.
CREATE TABLE user ( userId int(3) NOT NULL AUTO_INCREMENT,
username varchar(20) DEFAULT NULL, password varchar(20) DEFAULT
NULL, role varchar(20) DEFAULT NULL, PRIMARY KEY (userId),
UNIQUE KEY username (username) );
CREATE TABLE user_profile ( userId int(3) NOT NULL DEFAULT '0',
firstName varchar(20) DEFAULT NULL, lastName varchar(20) DEFAULT
NULL, PRIMARY KEY (userId), CONSTRAINT FK FOREIGN KEY
(userId) REFERENCES user (userId) );
Shouldn't following section in method enterUsername
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
be like this
ps.setInt(1, userId);
ps.setString (2, firstname);
ps.setString (3, lastname);
I don't see the reason for the error message that you posted.
But I see some other things that look like a problem:
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
The indexes are wrong: instead of 1, 1, 2, it should be 1, 2, 3.
(Frankly, I don't see how the code could possibly work as posted.)
Btw, this also looks wrong in the other method:
insert into user values(?,?,?)
As the table has more than 3 columns, you need to specify their names,
like you did in enterUsername.
Use
String q1 = "INSERT into user_profile (firstname, lastname) VALUES (?,?)";
because your first field is auto increment..So it automatically increment values while inserting values.
I recommended this way,
Delete your current table and create a new one like this
id-->int(30) (AUTO INCREMENT) NOTNULL //Dont need to take care of this field
USER_ID-->int(30) NOT NULL //you should create your own ID and increment it before adding a new person
username-->varchar(100)
password-->varchar(100)
role-->varchar(100)
and usually, call userId exactly same like your code,
String q0 = "Select userId from user ORDER BY USER_ID DESC LIMIT 1"; //get ID of last
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(q0);
if(rs.next()){
ID = rs.getInt("USER_ID ");
ID++;
}
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.