Database table update in vaadin - java

I was working with the following code to update my database table with the following code. Database connection is established, no exceptions shown, but my database table is not getting updated.
private void setupSaveButton(){
saveButton.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
try {
String updateQuery = "UPDATE " + MySqlConnectionManager.getDatabaseTableName()
+ " SET BUGID='" + bugIdTextField.getValue()
+ "', USERID='" + userIdTextField.getValue()
+ "', SUBJECT='" + subjectTextField.getValue()
+ "', COMMENT='" + commentTextArea.getValue()
+ "', STATUS='" + statusComboBox.getValue()
+ "', OWNER='" +ownerTextField.getValue()
+ "', PRIORITY='" + priorityComboBox.getValue()
+ "' WHERE DATE='"+dateTextField.getValue()+"'; ";
Connection connection = MySqlConnectionManager.getInstance().getConnection();
if(connection!=null){
Statement stmt = connection.createStatement();
System.out.println("Query " + updateQuery);
stmt.executeUpdate(updateQuery);
}
} catch (SQLException ex) {
Logger.getLogger(BugDetailDisplay.class.getName()).log(Level.SEVERE, null, ex);
}
}
});

I guess you are using DateField for date.
Default date format of MySql is YYYY-MM-DD while your dateTextField.getValue() will return Date Object and default toString representation of Date will be concatenated in your query.So,both formats are different and your query executes successfully but can not detect the row with date you get from dateTextField.You can use SimpleDateFormat to format result of dateTextField.getValue() to allow query to find matching row.
If you are using simple textField than make sure your date format must match with MySql date.

Related

How to update a row of entries in a database (JavaDatabase) that is connected to my JTable?

I am making a program without knowing much about programming... I used some youtube videos to help me.
My program is made for a chef that can edit users & food and gather ratings and suggestions from the inspector. The chef's section of editing users' details works.
However, the inspector's rating does not as it throws an error: SQLSyntaxException: Encountered "Vegetarian" at line 1, column 65. I believe it is because of getting the rating value (which is int) in a wrong way...
'
public void getConnection(){
try{
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1327/MyApp", "Me", "Me");
mystatObj=myconObj.createStatement();
myresObj=mystatObj.executeQuery("Select * from Me.Food");
tableRateFood.setModel(DbUtils.resultSetToTableModel(myresObj));
}
catch (SQLException e){
e.printStackTrace();
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "update Me.Food set Name = '" + nameText.getText()
+ "',Type = '" + typeText.getText()
+ "', Rating = '" + ratingText.getText()
+ ", 'Vegetarian = '" + vegetarianText.getText()
+ "', ShownOnMenu = '" + showText.getText()
+ "' where Id = " + idText.getText();
//tried the following... did not work either
/*+ " Rating = " + Integer.parseInt(ratingText.getText()));*/
Statement update= myconObj.createStatement();
update.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Updated successfully!");
}
catch(SQLException E){
E.printStackTrace();
}
getConnection();
}
Your forgot a quote in ", 'Vegetarian = '"
Talking about building query strings, you should avoid +-ing values and rely on prepared statements with sql parameters instead. Allows the database to cache the query and avoids sql injection attacks. And spares you formatting headache, think about date values.

MySQL Syntax Error Exception when executing Update query

I'm getting the message
"MySQLSyntaxErrorExcetpion You have an error in your SQL syntax."
I'm following a tutorial online and I don't see what's anything different with my code and the code I'm following. Can anyone point out where I went wrong?
Let me know if additional information is needed.
btn_update.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try{
theQuery("update users set fname = '" + firstNameField.getText() + "', lname = '" + lastNameField.getText() +"', age=" + ageField.getText() + "where id = " + idField.getText());
}
catch(Exception ex)
{
System.out.println(ex);
}
}
});
because you don't have spaces here:
age=" + ageField.getText() + "where id = " + idField.getText());
You need to change it to
age= " + ageField.getText() + " where id = " + idField.getText());
I advice to use PreparedStatement instead of the native way
Add a space in front of " where id = ".
That should work
Use toString() function to convert values to string and then pass them to query, as follow:
firstNameField.getText().toString()

Apache Derby ID column should auto increment one by one - but it does not, why?

I'm trying to create an Apache Derby-Table and to insert data in it by the JDBC-interface.
Here is a short excerpt of my implementation:
public class SQLDatabase {
private Connection connection = null;
public final static String HOME_DIRECTORY = System.getProperty("user.home");
public final static String TABLE_NAME = "PORPHYRIE";
public SQLDatabase() {
setConnection();
if (!(isTableExisting(TABLE_NAME))) {
createTable();
}
}
// OTHER
public void createTable() {
String statement = "CREATE TABLE PORPHYRIE("
+ "ID int NOT NULL GENERATED ALWAYS AS IDENTITY"
+ "(START WITH 1,INCREMENT BY 1)," + "ENTRYDATE DATE NOT NULL,"
+ "DRUGTYPE varchar(255) NOT NULL,"
+ "UPPERLIMIT DOUBLE NOT NULL," + "NORMOSANG BOOLEAN NOT NULL,"
+ "MENSTRUATION BOOLEAN NOT NULL,"
+ "DRUGAMOUNT_MG DOUBLE NOT NULL,"
+ "DRUGAMOUNT_ML DOUBLE NOT NULL,"
+ "AMPOULE_NUMBERS DOUBLE NOT NULL,"
+ "RECORDDATE DATE NOT NULL," + "PRIMARY KEY(ID)" + ")";
updateStatement(statement);
}
public void dropTable() {
String statement = "DROP TABLE PORPHYRIE";
updateStatement(statement);
}
public void addData(EntryPoint entry) {
DrugAmount drugAmount = entry.getDrugAmountObject();
SimpleDateFormat form = new SimpleDateFormat("dd.MM.yyyy");
String statement = "INSERT INTO PORPHYRIE (ENTRYDATE,DRUGTYPE,UPPERLIMIT,NORMOSANG,MENSTRUATION,DRUGAMOUNT_MG,DRUGAMOUNT_ML,AMPOULE_NUMBERS,RECORDDATE)"
+ " values('"
+ form.format(entry.getEntryDate().getTime())
+ "','"
+ entry.DRUG_TYPE_DOLANTIN
+ "',"
+ entry.DRUG_UPPER_LIMIT
+ ","
+ entry.getNormoSang()
+ ","
+ entry.getMenstruation()
+ ","
+ drugAmount.getAmpoulesInMG()
+ ","
+ drugAmount.getAmpoulesInML()
+ ","
+ drugAmount.getNumberOfAmpoules() + ",CURRENT_DATE)";
System.out.println("Add data!");
updateStatement(statement);
}
private void setConnection() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager.getConnection("jdbc:derby:"
+ HOME_DIRECTORY + "\\MyDB;create=true");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void updateStatement(String statementString) {
try {
PreparedStatement preparedStatement = getConnection()
.prepareStatement(statementString);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
This is what I get:
What is here the problem with the ID column?
The first time when a SQL-Database object is created, is should create the table, which works fine.
Then you should able to insert some data by the addData()-method, which also looks fine.
But if you create an new SQL-Database Object and use the addData-method() within, then it adds the data (row five in the picture above) but do not auto-increment correctly. What is wrong here?
Gaps in the generated sequence numbers are a correct and documented behavior of Derby.
See, for example, https://db.apache.org/derby/docs/10.9/ref/rrefproperpreallocator.html
And: https://issues.apache.org/jira/browse/DERBY-5151
the problem is we have to shut down the derby db whenever we are sign out or closing our application,then only the values will be inserted properly otherwise the cache values prevents the exact insertion value in database table.
follow below steps:
con = DriverManager.getConnection("jdbc:derby:" + "db" + ";create=true");->this is for loading derby db by mentioning 'db' name.this code we have to place in your application login action.
DriverManager.getConnection("jdbc:derby:"+"db"+";shutdown=true");->this is for closing the database 'db'.we have to place this code in your application logout action or closing place.
note : This is for Embedded DB
As Described by Bryan, this error is well known. But good thing is you can solve it by using:
DriverManager.getConnection("jdbc:derby:;shutdown=true");
This will shutdown all the databases that you have in derby, you can always specify the database you want to shutdown.
DriverManager.getConnection("jdbc:derby:" + HOME_DIRECTORY + "\\MyDB;shutdown=true")

Inserting data into table

Good evening.
I am doing a basic exercise to insert data into an Access Database Table and in the code lies a syntax error which I am struggling to pinpoint.
Was hoping could receive some help with that as to where that Syntax problem lies.
The error reads as follow
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
public void addData(String ID, String name, String address, String type) throws SQLException
{
int rowsadded;
Statement statement = conn.createStatement();
String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + ", " + type + "')";
System.out.println(queryString);
System.out.println(ID + "(ID) added to the database");
rowsadded = statement.executeUpdate(queryString);
System.out.println("Rows updated = " + rowsadded);
}
Method call happens as follow
Insertingdata example;
try
{
example = new Insertingdata();
example.addData("15", "Bob Dylan", "Los Angeles", "Folk");
}
catch(SQLException se)
{
se.printStackTrace();
}
catch(ClassNotFoundException ce)
{
ce.printStackTrace();
}
You missed a couple of single quotes in the query, so address and type were being read as a single value. Replace your queryString line with:
String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + "', '" + type + "')";
This should fix the problem.

Insert Date in Java to Access DB - Weird issue

I'm trying to update a table in my AccessDB and i'm having a weird problem.
The update executes without throwing any exceptions but the date value is wrong and
everytime i update a record the value always changes to "30/12/1899".
Same thing hapens when i'm trying to insert a new record.
In my DB the Date field is in ShortDate format.
Here is an example of my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
if (jList1.isSelectionEmpty()) {
JOptionPane.showMessageDialog(null, "You have not selected any computer!");
} else {
try {
String sql = "Update SYSTEMS set "
+ " CPU='" + cpuTextField.getText().trim()
+ "', MOBO='" + moboTextField.getText().trim()
+ "', RAM='" + ramTextField.getText().trim()
+ "', GPU='" + gpuTextField.getText().trim()
+ "', HDD='" + hddTextField.getText().trim()
+ "', PSU='" + psuTextField.getText().trim()
+ "', MONITOR='" + monitorTextField.getText().trim()
+ "', KEYBOARD='" + keyboardTextField.getText().trim()
+ "', MOUSE='" + mouseTextField.getText().trim()
+ "', OS='" + osTextField.getText().trim()
+ "', SOFTWARE='" + othersTextArea.getText().trim()
+ "', PURCHASE_DATE=" + df.format(jDateChooser1.getDate())
+ " where SYSTEM_ID='" + jList1.getSelectedValue().toString() + "'";
st = con.prepareStatement(sql);
st.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
JOptionPane.showMessageDialog(null, "Updated");
}
}
In order to figure out what is going wrong, I made a button and when pressed i had
a Message showing the result of df.format(jDateChooser1.getDate()) and
it showed the correct date.
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
JOptionPane.showMessageDialog(null, df.format(jDateChooser1.getDate()));
}
I'm using this component to get the date: JCalendar If that makes any difference.
I dont mind replacing it with a plain TextField, as long as the date is imported correctly.
When using select to retrieve the date from the DB everything goes well.
The problem only occurs when updating/inserting.
The problem likely has to do with the formatting of the SQL query; use a PreparedStatement instead of formatting it manually. Doing so will also decrease the likelihood of errors related to validating user input, including security issues such as SQL injection. For example:
String sql = "Update SYSTEMS set "
+ " CPU=?, MOBO=?, RAM=?"
+ //...
+ ", PURCHASE_DATE=?"
+ " where SYSTEM_ID=?";
PreparedStatement stmt = con.prepareStatement(sql);
int nextField = 1;
stmt.setString(nextField++, cpuTextField.getText().trim());
stmt.setString(nextField++, moboTextField.getText().trim());
stmt.setString(nextField++, ramTextField.getText().trim());
// ...
stmt.setDate(nextField++, jDateChooser1.getDate());
stmt.setString(nextField++, jList1.getSelectedValue().toString());
stmt.executeUpdate();
[Edit] Note that the PreparedStatement#setDate() method requires a java.sql.Date, so you may need to convert the date type returned by your date chooser into one of those, e.g.:
stmt.setDate(nextField++,
new java.sql.Date(jDateChooser1.getDate().getTime()));
Access requires dates to specified in format #MM/dd/yyyy# (including the hash marks). So if you add the # delimiters at the beginning and end of the date string, it should work. As maerics suggested, the best would be to use PreparedStatement, because the JDBC drive will handle converting Java Date to the format Access understands, without you needing to format the value.
Looks like your date format is different from what Access expects.
To get rid of it, use name parameters - as at http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html#supply_values_ps, rather than concatenating the SQL on your own.

Categories

Resources