Update mysql database in Java - java

Can anybody point out what's wrong with my code? I am trying to update an attribute but I got an error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for
column 'phone' at row 1
Is there anything wrong with the SQL command? Thank you!
String queryString = "";
String selectedItem = (String) searchTypeCmb.getSelectedItem();
String searchTerm = searchTermField.getText();
String id = theId.getText();
textArea.setText("");
if ("Phone".equals(selectedItem)) {
queryString = "UPDATE person SET phone = '" + (searchTerm) +
" WHERE driverID = " + (id) + "'";
}
else if ("Address".equals(selectedItem)) {
queryString = "UPDATE person SET address = '" + (searchTerm) +
" WHERE driverID = " + (id) + "'";
}
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/dealer", "root", "admin");
statement = connection.createStatement();
statement.executeUpdate(queryString);
Here is my DB schema
create table person
( driverID int unsigned not null primary key,
firstName char(20) not null,
lastName char(20) not null,
address char(30) not null,
phone char(20)
);
create table cars
( license char(10) not null,
brand char(20) not null,
model char(20) not null,
year char(10),
status char(10) not null,
carID int unsigned not null primary key
);

To start with, your missing closing quotes around your text...
"UPDATE person SET phone = '" + (searchTerm) + " WHERE driverID = " + (id) + "'"
^-----------------------------^
Which you probably want to be
"UPDATE person SET phone = '" + (searchTerm) + "' WHERE driverID = " + (id)
But having said that, I'd strongly encourage you to use PreparedStatements instead.
String queryString = "";
String selectedItem = (String) searchTypeCmb.getSelectedItem();
String searchTerm = searchTermField.getText();
String id = theId.getText();
textArea.setText("");
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/dealer", "root", "admin")) {
PreparedStatement stmt = null;
if ("Phone".equals(selectedItem)) {
stmt = connection.prepareStatement("UPDATE person SET phone = ? WHERE driverID = ?");
} else if ("Address".equals(selectedItem)) {
stmt = connection.prepareStatement("UPDATE person SET address = ? WHERE driverID = ?");
}
if (stmt != null) {
stmt.setString(1, searchTerm);
stmt.setString(2, id);
stmt.executeUpdate();
}
See Using Prepared Statements for more details...

If you have the message
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'phone'
The data that you are writing in the column "phone" is longer than the maximum length of that field on the database.
So you can:
Truncate the phone value before inserting it in the database
Alter your column length in the database

Related

Why SAVE button is not saving to MySQL database in Java code

What's wrong with the code, no errors but still it's not saving to database, where did it go wrong?
Even if the database is created, the code won't store the values
JButton btnSave = new JButton("SAVE");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get Breed and age entered by user
String breed = textBreed.getText();
String breed_age = textAge.getText();
// Convert age into integer
int age = Integer.parseInt(breed_age);
// Connection
try {
//open connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/animal_db", "root", "root");
// Insert data into table
Statement stm = con.createStatement();
String dog_table = "CREATE TABLE IF NOT EXISTS breedtest" +
"(id INT NOT NULL AUTO_INCREMENT," +
"breed VARCHAR(30)," +
"age INT," +
"PRIMARY KEY (id))";
stm.executeUpdate(dog_table);
String sql = "INSERT INTO breedtest VALUES ('"+textBreed.getText()+"', "+textAge.getText()+")";
// Execute Statement
stm.executeUpdate(sql);
// display message of record inserted
JOptionPane.showMessageDialog(btnSave, "Record added");
textBreed.setText("");
textAge.setText("");
//Close connection
con.close();
}catch(Exception E) {
}
}
});
textBreed & textAge are text field from the GUI
here is a creen shot of the GUI.
enter image description here
I have amended the following lines, and it works fine
// Insert data into table
Statement stm = con.createStatement();
String dog_table = "CREATE TABLE IF NOT EXISTS breedtest" +
"(id INT NOT NULL AUTO_INCREMENT," +
"breed VARCHAR(30)," +
"age INT," +
"PRIMARY KEY (id))";
stm.executeUpdate(dog_table);
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES(?, ?)";
PreparedStatement brd = con.prepareStatement(sql);
brd.setString(1, textBreed.getText());
brd.setString(2, textAge.getText());
brd.execute();
data got captured in database with the confirmation message.
Displayed message
Database table
This line of code is not executing
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES ("+textBreed.getText()+", "+textAge.getText()+")";
but this one is.
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES(?, ?)";
I understand that in my first code I omitted to name the columns, thanks for flagging this.
Could someone explain me which line of code is associating the "VALUES(?, ?)" to the textfield.
You need to modify your Insert query with the following
String sql = "INSERT INTO breedtest(breed, age) VALUES ('"+textBreed.getText()+"', "+textAge.getText()+")";

Can't Update the SQL through Java

I'm trying to make CRUD (Create, Read, Update, Delete) to my projects. But it seems the "update" doesn't work. It keeps saying
java.sql.SQLSyntaxErrorException : You have an error in your SQL syntax; check the manual that coresponds to your MariaDB server version for the right syntax to use near "Number" = 0813874810 WHERE Name = "Gregory" at line 1)
What the solution for this?
Here is my code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata", "root", "");
String sql = "UPDATE employeetab SET Name = '" + txtEmployeeName.getText()
+ "',Address = '" + txtEmployeeAddress.getText()
+ "',Gender = '" + gender_type
+ "',Phone Number = '" + txtEmployeePhone.getText()
+ "' WHERE Name = '" + txtEmployeeName.getText() + "'";
stm = conn.prepareStatement(sql);
stm.execute(sql);
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
Problem comes from the space in column Phone Number. To make it work you need to escape the column name with `.
UPDATE employeetab
SET Name = 'something',Address = 'some address',Gender = 'whatever',`Phone Number` = '000000000'
WHERE Name = 'something';
You should follow sql naming conventions, normally words in column names are separated by _. Your column name should be - phone_number.
Also, as mentioned in comments, you should not just add user input into sql queries, because you are leaving yourself wide open for sql injection.
You need to follow the naming conventions , their is space between 'Phone Number' column you should not write like this you need to add _ in between of this two.
try this :
String gender_type = null;
if (ButtonM.isSelected()){
gender_type = "Male";
}else if(ButtonFM.isSelected()){
gender_type = "Female";
}
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata","root","");
String sql = "UPDATE employeetab SET Name = ? ," +
" Address = ? ," +
" Gender = ? ," +
" Phone Number = ? ," +
" WHERE Name = ? ," ;
PreparedStatement pStmt = conn.prepareCall(sql);
pStmt.setString(1, txtEmployeeName.getText()+"");
pStmt.setString(2, txtEmployeeAddress.getText()+"");
pStmt.setString(3, gender_type+"");
pStmt.setString(4, txtEmployeePhone.getText()+"");
pStmt.setString(5, txtEmployeeName.getText());
pStmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
its cleaner and should work.

cannot set null to a unique column

so this is my table
CREATE TABLE "client" (
"id" INTEGER,
"name" TEXT COLLATE NOCASE,
"surname" TEXT COLLATE NOCASE,
"number" TEXT UNIQUE COLLATE NOCASE,
"car_brand" TEXT,
"modele" TEXT,
"phone_nbr" TEXT,
PRIMARY KEY("id" AUTOINCREMENT));
when im adding a new statment from my java application i can add only one time NULL to the column number but i can add many nulls from the db browser
this is the code that i use
String number = tf_number.getText();
if(tf_number.getText().trim().isEmpty())
number = null;
String name = tf_name.getText();
String surname = tf_surname.getText();
String phoneNbr = tf_phoneNbr.getText();
String car_brand = tf_brand.getText();
String modele = tf_modele.getText();
Client c = new Client(name, surname, number, car_brand, modele, phoneNbr);
ClientCRUD pcd = new ClientCRUD();
pcd.addClient(p);
and this is the sql error
[SQLITE_CONSTRAINT_UNIQUE] A UNIQUE constraint failed (UNIQUE constraint failed: client.number)
this is the addClient() fonction
public void addClient(Client t) {
try {
String requete = "INSERT INTO CLIENT(name,surname,number,car_brand,MODELE,phone_nbr)"
+ "VALUES ('"+t.getClientName()+"','"+t.getClientSurname()+"','"+t.getNumber()+"',"
+ "'"+t.getCarBrand()+"','"+t.getModele()+"','"+t.getPhone()+"')";
Statement st = MyConnection.getInstance().getCnx()
.createStatement();
st.executeUpdate(requete);
System.out.println("Client added");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
any solution ?
public void save(Person person) {
String query = "INSERT INTO person_info (" +
" name_p, " +
" age, " +
" address, " +
" email " +
")" +
"VALUES(?, ?, ?, ?)";
try(Connection connection = dbConnection.getConnection()) {
PreparedStatement prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, person.getName());
prepStatement.setInt(2, person.getAge());
prepStatement.setString(3, person.getAddress());
prepStatement.setString(4, null);
prepStatement.execute();
}
catch (SQLException e){
e.printStackTrace();
}
}
##This will solve your problem
You code inserts the string "null" and not a real null like your browser do.
So there can be only 1 string with value "null" in that unique column.
You can use preparedStatement with parameters instead of the statement you use.
E.g:
PreparedStatement preparedStatement = connection.prepareStatement(sql))
This answers how to insert null using prepared statement: Insert null using prepared statement
And your sql string for the query should have the parameters.
See more about prepared statements: Prepared Statements Tutorial

Java SQL (JDBC) : how to move to the next column?

I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?
Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.

Executing the second query only the first query is executed

I want to make a function in java that executes two queries, in which I want to do this:
Example:
String s ="CREATE TABLE ClassRoom(ID int AUTO_INCREMENT PK ,
name char (2) not null,
section char (2) not null,
numberSt int not null,
)";
String s1 ="INSERT INTO ClassRoom VALUES (null,'5','A',25)";
pst = conn.prepareStatement(s);
pst.executeUpdate();
pst = conn.prepareStatement(s1);
pst.executeUpdate();
I want to put some values in the table when I create the table.
The first time it works perfectly, but the second time s is not called as there is IF NOT EXISTS, but the s1 is called again another time.
I want the s1 to be called only if the s has been executed or the table has been created. IF the table already exists i don't want to call s1 query.
Depending on your SQL database the easiest way will be to use an upsert. This inserts the data already if it doesn't exist, updating otherwise. You would need to remove the generated key and use a compound key from whatever values uniquely identify the room though.
You can check if the table exists with the following query:
SELECT *
FROM information_schema.tables
WHERE table_schema = 'yourdb'
AND table_name = 'ClassRoom'
LIMIT 1;
You have to test if the table has been created.
boolean existsTable = false;
// use significative variable names... always!
String createQuery =
"CREATE TABLE ClassRoom( " +
"ID int AUTO_INCREMENT PK, " +
"name char (2) not null, " +
"section char (2) not null, " +
"numberSt int not null, " +
")";
String defaultValuesQuery ="INSERT INTO ClassRoom VALUES (null,'5','A',25)";
String checkTableQuery = "SELECT * " +
"FROM information_schema.tables " +
"WHERE table_schema = 'yourdb' " +
"AND table_name = 'ClassRoom' " +
"LIMIT 1;";
PreparedStatement pst = conn.prepareStatement(checkTableQuery);
ResultSet rs = pst.executeQuery();
// if the check query returns some value then table exists!
if (rs.next()) {
existsTable = true;
// if table don't exists, create it
} else {
pst = conn.prepareStatement(createQuery);
pst.executeUpdate();
}
// execute query only if table exists
if (existsTable) {
pst = conn.prepareStatement(defaultValuesQuery);
pst.executeUpdate();
}

Categories

Resources