Why is this SQL not contained in the try Catch - java

Why is the SQL not in the try catch, Problem is I tried using two separate try catches but then the SQL statement could not reference the FileInputStream variable and this was the alternative I came up with but it didn't seem to work
try {
final FileInputStream FIS = new FileInputStream(ReturnFile);
JButton Submit = new JButton ("Insert");
Submit.setLocation (430, 335);
Submit.setSize (150, 25);
newCarFrame.add(Submit);
Submit.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
Connection Con = new DataBaseHandler().GetConnection();
Statement stmt = Con.createStatement();
String SQL = "INSERT INTO Cars (`Reg_No`, `Car_Image`, `Make`, `Model`, `Mileage`, `Date_Of_Purchase`, `Price`, `Storage_Location`, `Body_Type`, `Gearbox`, `Age`, `No_Of_Doors`, `Colour`, `Fuel_Type`, `Engine_Size`, `Description`) VALUES ('" + RegNoTextBox.getText() + "', '" + FIS + "', '" + MakeComboBox.getSelectedItem() + "', '" + ModelTextBox.getText() + "', '" + MillageTextBox.getText() + "', '" + DOPField.getText() + "', '" + PriceField.getText() + "', '" + StorageCombo.getSelectedItem() + "', '" + BodyTypesCombo.getSelectedItem() + "', '" + GearBoxValue + "', '" + No_Of_Doors_Combo.getSelectedItem() + "', '" + AgeField.getText() + "', '" + ColourField.getText() + "', '" + PetrolValue + "', '" + EngineSizeField.getText() + "', '" + DescriptionField.getText() + "')";
System.out.println(SQL);
//Execute the SQL query
//TODO Salt the password
stmt.executeUpdate(SQL);
Con.close();
String ShowAllSalesSQL = "SELECT * FROM `Cars`";
SalesWindow MSW = new SalesWindow (ShowAllSalesSQL);
}
});
} catch (FileNotFoundException e2) {
System.out.println("No File");
e2.printStackTrace();
} catch (SQLException e1) {
}
All help is greatly appreciated thanks.

That's because when you do this Submit.addActionListener(new ActionListener () { ... } you are actually implementing a ActionListener interface inline, as anonymous class. In that try block you are only setting the action listener instance to Submit button, you are not actually surrounding the code which will be executed when the button is clicked.

Sorry I was being stupid I fixed it as shown below
JButton Submit = new JButton ("Insert");
Submit.setLocation (430, 335);
Submit.setSize (150, 25);
newCarFrame.add(Submit);
Submit.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
try {
final FileInputStream FIS = new FileInputStream(ReturnFile);
Connection Con = new DataBaseHandler().GetConnection();
Statement stmt = Con.createStatement();
String SQL = "INSERT INTO Cars (`Reg_No`, `Car_Image`, `Make`, `Model`, `Mileage`, `Date_Of_Purchase`, `Price`, `Storage_Location`, `Body_Type`, `Gearbox`, `Age`, `No_Of_Doors`, `Colour`, `Fuel_Type`, `Engine_Size`, `Description`) VALUES ('" + RegNoTextBox.getText() + "', '" + FIS + "', '" + MakeComboBox.getSelectedItem() + "', '" + ModelTextBox.getText() + "', '" + MillageTextBox.getText() + "', '" + DOPField.getText() + "', '" + PriceField.getText() + "', '" + StorageCombo.getSelectedItem() + "', '" + BodyTypesCombo.getSelectedItem() + "', '" + GearBoxValue + "', '" + No_Of_Doors_Combo.getSelectedItem() + "', '" + AgeField.getText() + "', '" + ColourField.getText() + "', '" + PetrolValue + "', '" + EngineSizeField.getText() + "', '" + DescriptionField.getText() + "')";
System.out.println(SQL);
//Execute the SQL query
//TODO Salt the password
stmt.executeUpdate(SQL);
Con.close();
String ShowAllSalesSQL = "SELECT * FROM `Cars`";
SalesWindow MSW = new SalesWindow (ShowAllSalesSQL);
} catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e3) {
e3.printStackTrace();
}
}
});

Related

Added data from CSV File to Java Derby Database deletes after closing the window

I have made a code to enable the user to upload a CSV file and add it to a derby database in Intellij. It works, but when the window is closed the data is gone. I'm using JavaFX and Java.
That's the method in the adapter class.
//update the table with new csv file
public void editData(File path)throws SQLException {
String line = "";
Statement stmt = connection.createStatement();
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
//storing the csv file values in an array and removing all the commas that are existing in the file
String[] values = line.split(",");
//for (int i = 0; i < values.length; i++) {
// stmt.executeUpdate("UPDATE am60Data SET Temperature ='" + values[0].toString() + "',Strain = '" + values[1].toString() + "', Stress = '" + values[2].toString() + "', True_Strain = '" + values[3].toString() + "',True_Stress = '" + values[4].toString() + "' , " +
// "StrainRate = '" + values[4].toString() + "', Aloy_id = '" + values[4].toString() + "' ");
stmt.executeUpdate("INSERT INTO am60Data (Temperature,Strain,Stress,True_Strain,True_Stress,StrainRate,Aloy_id ) " +
"VALUES('" + values[0].toString() + "', '" + values[1].toString() + "', '" + values[2].toString() + "', '" + values[3].toString() + "', '" + values[4].toString() + "','" + values[4].toString() + "','" + values[4].toString() + "' )");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//method to edit the publishing unit
That's the method in the controller that's connected to my FXML file.
public void save()
{
try {
AM60adapter= new AM60Adapter(conn, true);
AM60adapter.editData(new File(filePath.getText()));
buildData();
AM60adapter.getDataValues();
// NOTE: This value is specific for Java DB
String DB_URL = "jdbc:derby:MeridianDB;create=true";
// Create a connection to the database
conn = DriverManager.getConnection(DB_URL);
AM60adapter = new AM60Adapter(conn, true);
compositionAdapter = new AM60CompositionAdapter(conn, true );
summaryAdapter = new AM60SummaryAdapter(conn, true);
creepAdapter = new AM60CreepAdapter(conn, true);
//when the user clicks on the cancel button
} catch (SQLException ex) {
displayAlert("ERROR: " + ex.getMessage());
}
}
All the inserted data disappears after closing the window. Please anyone help!

How to insert the value of DateButton into a table through sql in java

String sql = "INSERT INTO Buses ( RegNo,BusNo, Model, Capacity, DatePurchased,InsuranceStatus,DateInsured,ExpiryDate) VALUES ('"
+ txtRegNo.getText() + "', '"
+ txtBusNo.getText() + "', '"
+ txtModel.getText() + "', '"
+ txtCapacity.getText() + "', '"
+ date_bought.getText() + "', '"
+ txtIStatus.getText() + "', '"
+ date_ins.getText() + "', '"
+ date_expiry.getText() + "')";

Java/UCanAccess Insert not working right

last week we got an assignment at school to develop a web Application for students, so they can use them to organize drives to school. The whole project is focused on project management and not on the programming part.
In my team we decided to make a GWT-Application because were all JAVA-Developers.
On the Server side I'm having trouble with our Microsoft Access DB I need to Insert a given dataset in the database, from the frontend I get an createObject which contains all the Information needed to be Insertet. My method looks like this:
#Override
public void makeOffer(CreateObject createobject) {
SecurityContext securityContext = SecurityContextHolder.getContext();
if(!securityContext.getAuthentication().isAuthenticated()) {
return;
}
String userName = securityContext.getAuthentication().getPrincipal().toString();
String teacher = "n";
if(userName.length() < 3) {
teacher = "y";
}
String sql = "INSERT INTO T_FAHRTEN "
+ "(F_SEATS, F_FREESEATS, F_CAR, F_TIME, F_SMOKE, F_GENDER, F_TEACHER, F_INFOS, F_NAME, F_VORNAME, F_NUMMER, F_MAIL, F_STARTTOWN, F_STARTSTREET, F_STARTPLZ, F_DATE, F_USERNAME)"
+ "Values ("
+ "'" + createobject.getSeats() + "', "
+ "'" + createobject.getFreeSeats() + "', "
+ "'" + createobject.getCar() + "', "
+ "'" + createobject.getTime() + "', "
+ "'" + createobject.getSmoke() + "', "
+ "'" + createobject.getGender() + "', "
+ "'" + teacher + "', "
+ "'" + createobject.getInfo() + "', "
+ "'" + createobject.getName() + "', "
+ "'" + createobject.getVorname() + "', "
+ "'" + createobject.getTelNummer() + "', "
+ "'" + createobject.getEmail()+ "', "
+ "'" + createobject.getStartStadt() + "', "
+ "'" + createobject.getStartStreet() + "', "
+ "'" + createobject.getStartPlz()+ "', "
+ "'" + createobject.getDate() + "', "
+ "'" + userName + "'"
+ ");";
Connection conn = null;
Statement stm = null;
try {
//FIXME
String dbURL = getClass().getResource("Drive2Gether2School1.accdb").getPath();
conn = DriverManager.getConnection("jdbc:ucanaccess://" + dbURL);
stm = conn.createStatement();
stm.executeUpdate(sql);
} catch (SQLException e) {
System.out.println("==> error creating");
e.printStackTrace();
//TODO implement Error Handling
} finally {
try {
if(stm != null) stm.close();
if(conn != null) conn.close();
} catch (SQLException e) {
System.out.println("==> error closing");
//TODO implement Error Handling
}
}
System.out.println("==> offer createt");
}
The Problem is, the data doesnt't get Insertet into the Access DB.
Actual its kinda weird, I have a method which gives me everything from the table and shows it on the Frontend. And If I insert something and then show everything I see the stuff I just insertet, but if I open the Tabel in MS-Access the Inserts are not there.
I already tried conn.commit and conn.setAutoCommit(true) both not helping.

Sqlite Database not updating using java

I am trying to update my new database but for some reason after executing my Prepared Statement the data remains the same. It returns no errors or any exceptions. Please have a look at my code and see if you can help me. Thanks in advance.
try {
connect();
PreparedStatement update = con.prepareStatement("UPDATE generalInfo SET "
+ "site" + " = '"
+ siteTt + "' , "
+ "area" + " = '"
+ areaTt + "' , "
+ "unit" + " = '"
+ unitTt + "' , "
+ "unitName" + " = '"
+ unitNameTt + "' , "
+ "drawing" + " = '"
+ drawingTt + "' , "
+ "system" + " = '"
+ systemTt + "' , "
+ "stream" + " = '"
+ streamTt + "' , "
+ "product" + " = '"
+ productTt + "' , "
+ "equipmentLoc" + " = '"
+ equipLocTt + "' , "
+ "specificLoc" + " = '"
+ specificLocTt + "' , "
+ "camOperator" + " = '"
+ camTechTt + "' , "
+ "camSerial" + " = '"
+ camSerialTt + "' , "
+ "gasSurveyOperator" + " = '"
+ surveyTechTt + "' , "
+ "gasSurveySerial" + " = '"
+ surveySerialTt + "' , "
+ "equipmentDesc" + " = '"
+ equipDescTt + "' , "
+ "equipmentType" + " = '"
+ equipTypeTt + "' , "
+ "equipmentSize" + " = '"
+ equipSizeTt + "' , "
+ "equipmentID" + " = '"
+ equipIDTt + "' , "
+ "[Maintenance type]" + " = '"
+ repairTt + "' , "
+ "measurementPosition" + " = '"
+ sourceTt + "'"
+ " WHERE leakerID = " + Integer.parseInt(leakerIDCombo.getSelectedItem().toString())+";");
update.closeOnCompletion();
update.executeUpdate();
con.close();
System.out.println("saved");
} catch (SQLException ex) {
Logger.getLogger(RefineryData.class.getName()).log(Level.SEVERE, null, ex);
}
never forgett to commit your changes:
con.setAutoCommit(true);
update.closeOnCompletion();
update.executeUpdate();
con.close();
or
update.closeOnCompletion();
update.executeUpdate();
con.commit();
con.close();

Error in linking mysql and netbeans data

I am working with mysql and Netbeans java for my school project. Whenever I try to register the details to the sql, I get this error My SqlSyntaxErrorException:Unknown Column " [the data in the text field] in 'field list'"
Here's my code:
int age = Integer.parseInt(AgeTF.getText());
String name=NameTF.getText();
String id=IDTF.getText();
String dob=DobTF.getText();
String address=AddressTF.getText();
try {
Class.forName("java.sql.Driver");
String database = "jdbc:mysql://localhost:3306/final";
Connection conn = DriverManager.getConnection(database, "root", "sanchit");
Statement stmt = conn.createStatement();
String sql = "insert into aadhar values ( '" + id + "', " + name + ", '" + dob + "' , '" + age + "' , '" + address + "' );" ;
stmt.executeUpdate(sql);
}
catch( Exception e){
JOptionPane.showMessageDialog(null,"" + e);
}
JOptionPane.showMessageDialog(this,"You have been registered!");
Please help.
Thanks
You didn't protect name with simple quotes :
Write '" + name + "' instead of " + name + "
String sql = "insert into aadhar values ( '" + id + "', '" + name + "', '" + dob + "' , '" + age + "' , '" + address + "' );" ;

Categories