Data Added twice in to the database using JTable java - java

i am trying to add my all data in the Jtable to the mysql database. but data added successfully. but Data Added twice into the database. I attached the screenshot below of database table how record added
enter image description here
this is the code which i tried
try{
int rows=jTable1.getRowCount();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root","");
con1.setAutoCommit(false);
String queryco = "Insert into sales_product(product,price) values (?,?)";
PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(queryco,Statement.RETURN_GENERATED_KEYS);
for(int row = 0; row<rows; row++)
{
String product = (String)jTable1.getValueAt(row, 0);
String price = (String)jTable1.getValueAt(row, 1);
preparedStmt.setString(1, product);
preparedStmt.setString(2, price);
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
preparedStmt.addBatch();
preparedStmt.executeBatch();
con1.commit();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch(ClassNotFoundException | SQLException | HeadlessException e){
JOptionPane.showMessageDialog(this,e.getMessage());
}

As in your code you are iterating each row one by one and on every iteration you are executing both :
preparedStmt.executeUpdate();
preparedStmt.executeBatch();
That's why same row has been inserted twice.
You can go with below solutions to avoid multiple insertion.
Only use preparedStmt.executeUpdate(); within the loop and remove preparedStmt.executeBatch();
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
// preparedStmt.addBatch();
// preparedStmt.executeBatch();
con1.commit();
}
Don't use preparedStmt.executeUpdate(); and move preparedStmt.executeBatch(); outside of loop.
//preparedStmt.executeUpdate();
//ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
preparedStmt.addBatch();
}
preparedStmt.executeBatch();
con1.commit();

Related

Update one column from table and insert new rows. sqlite, java

I have some problems to modify data from a table.
I need to update an entire column from a specific table and if there's no sufficient rows I need to insert more.
More exactly, the user will be able to modify data from interface, in a text area that contains current data from db.
I put all the text in a list, each line representing an element of the list.
In a certain column, I must go through each row and modify it with a list item. If there are more lines in the text area than number of rows in that table, I need to insert new ones, which will contain the remaining items from the list.
I would be grateful if someone could give me some help.
Thanks!
#FXML
public void modify() throws SQLException {
String col= selectNorme.getValue().toString();
String text=texta.getText();
List<String> l1notes= new ArrayList<>( Arrays.asList( text.split("\r\n|\r|\n") ));
Statement stmt=null;
String client = this.clientCombobox.getValue().toString();
String tab1Client= client+ "_" +this.selectLang1.getValue().toString();
String query="SELECT * FROM "+tab1Client+" WHERE ["+ selectNorme.getValue().toString()+ "]= "+col+"";
String sqlUpdate1= "UPDATE ["+tab1Client+"] SET ["+ this.selectNorme.getValue().toString() +"] = ?";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement modif=conn.prepareStatement(sqlUpdate1);
int i=0;
if (rss.next()) {
stmt = conn.createStatement();
rss = stmt.executeQuery(query);
stmt.executeUpdate(sqlUpdate1);
modif.setString(1, l1notes.get(i));
i++;
modif.execute();
}
else {
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO ["+this.clientCombobox.getValue().toString()+"_"+this.selectLang1.getValue().toString()+"] (["+ this.selectNorme.getValue().toString() +"]) values (?)" );
for (int row=i; row< l1notes.size(); row++)
{
pstmt.setString(1, l1notes.get(row));
pstmt.executeUpdate();
}
}
}
finally {
try {
if (conn !=null)
conn.close();
}
catch (SQLException se){
se.printStackTrace();
}
}
}

How to get auto generated keys of batch insert statement?

I want to INSERT batch of records in a database (i.e. DB2) using JDBC batch statement and then obtain the auto generated IDs of inserted rows. How can I achieve using JDBC API?
Example Code:
String SQL_INSERT = "INSERT INTO TABLE1 (CURRENT_TIMESTAMP) VALUES (?) ";
Connection connection = DriverManager.getConnection("jdbc:db2://localhost:900/DATABASE");
PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);
// first batch
statement.setTimestamp(1, getCurrentTimestamp());
statement.addBatch();
// second batch
statement.setTimestamp(1, getCurrentTimestamp());
statement.addBatch();
int[] insertedRows = statement.executeBatch();
ResultSet generatedKeys = statement.getGeneratedKeys();
The batch statement executes successfully, all rows inserted into database. But when calling getGeneratedKeys() to retrieve generated keys, it returns an empty ResultSet. Any idea, why?
I have managed to find the db2 specific solution. If the PreparedStatement object returns automatically generated keys, call DB2PreparedStatement.getDBGeneratedKeys to retrieve an array of ResultSet objects that contains the automatically generated keys.
import com.ibm.db2.jcc.DB2PreparedStatement;
// more code here
ResultSet[] result = ((DB2PreparedStatement) preparedStatement).getDBGeneratedKeys();
for (int i = 0; i < result.length; i++) {
while (result[i].next()) {
ResultSet rs = result[i];
java.math.BigDecimal generatedKey = rs.getBigDecimal(1);
System.out.println("Automatically generated key value = " + generatedKey);
}
}
objPsmt.executeBatch();
try (ResultSet rs = objPsmt.getGeneratedKeys()) {
if (rs != null) {
while (rs.next()) {
int generatedId = rs.getInt(1);
generatedIds.add(generatedId);
}
}
} catch (Exception e) {
LOGGER.error("Exception while generating ids ", e);
}

Insert values of arraylist into mysql table

I am trying to insert values from arraylist into mysql table.
List lstUnique=new ArrayList<Object>();
//code to feed the data into list from resultset.
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/MYdb","root","");
stmt=con.createStatement();
String sql1="select SourceFrom,Updated,Location_Type,Industry,ET_Rank,BT_Rank from mytable";
rs1=stmt.executeQuery(sql1);
rsmd=rs1.getMetaData();
columnNumber=rsmd.getColumnCount();
while(rs1.next()){
lstUnique.add(rs1.getString("SourceFrom")+","+rs1.getString("Updated")+","+rs1.getString("Location_Type")+","+
rs1.getString("Industry")+","+rs1.getString("ET_Rank")+","+rs1.getString("BT_Rank"));
}
String insertsql="";
String SourceFrom=lstUnique.get(0).toString(); //its first column of the table.
insertsql="Insert into java_uniquedata (SourceFrom,field2,field3,field4,field5) values(?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(insertsql);
//I tried this way also.
for(int i=0;i<lstUnique.size();i++){
SourceFrom=lstUnique.get(i).toString();
}
for(int i=0;i<lstUnique.size();i++){
System.out.println("\n" + lstUnique.get(i).toString());
}
rs1.close();
con.close();
}catch(Exception e){
System.out.println(e);
}
But I am getting error
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
My list has only one record in it, which has total 5 columns' values. Can you guide me how do I fetch values of first record from arraylist and insert it into mysql table.
You should separate the values for your insert statement. Either use a custom datastructure (class) or use a List<String>.
Something like this might work:
List<List<String>> lstUnique=new ArrayList<>(); // note the List of List
try {
/* ... your database query here ... */
while(rs1.next()){
List<String> values = new ArrayList<>(); // create list for values
values.add(rs1.getString("SourceFrom"));
values.add(rs1.getString("Updated"));
values.add(rs1.getString("Location_Type"));
values.add(rs1.getString("Industry"));
values.add(rs1.getString("ET_Rank"));
values.add(rs1.getString("BT_Rank"));
lstUnique.add(values); // add values for each row
}
String insertsql="Insert into java_uniquedata (SourceFrom,field2,field3,field4,field5) values(?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(insertsql);
for(List<String> values : lstUnique) { // use for each for rows
for(int i=0;i<values.size();i++) { // set argument values to prepared statement
ps.setString((i+1), values.get(i));
}
ps.execute(); // execute insert statement
}
ps.close();
} catch(Exception e){
System.out.println(e);
} finally { // close recordset and connection in finally-block! (or use 'try-with-resource'!)
rs1.close();
con.close();
}
try this one
for(int i=0; i < lstUnique.size();i++){
ps.setString(1, lstUnique.get(i).toString());
}
ps.execute(insertsql);
I tried this and it inserts data into database
ArrayList<String> lis = new ArrayList<String>();
lis.add("pare1");
lis.add("2");
//code to feed the data into list from resultset.
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "paresh");
String insertsql="";
insertsql="Insert into stud (name,age) VALUES (?,?)";
PreparedStatement ps=connection.prepareStatement(insertsql);
//this will set value for your insert statement
System.out.println(lis.get(0).toString());
ps.setString(1, lis.get(0).toString());
ps.setInt(2, Integer.parseInt(lis.get(1)));
System.out.println(ps);
ps.execute(insertsql);
Completely different aproach for a solution to the task, if it is not mandatory to be solved in Java(?):
Since your code sample gives the impression that you're reading from and writing to the same database, you might also consider to copy the data in-database using the SQL INSERT-SELECT Syntax:
INSERT INTO java_uniquedata (SourceFrom, field2, field3, field4, field5)
SELECT DISTINCT SourceFrom, Updated, Location_Type, Industry, ET_Rank, BT_Rank
FROM mytable;
See MySQL INSERT ... SELECT Syntax.

Updating database from a dynamic jtable

I am trying to update a database from a dynamic JTable. Here is my code
try {
//open connection...
conn = javaConnect.ConnectDb();
//select the qualifications table row for the selected staffID
String sql2 = "select * from QualificationsTable where qualID =" + theRowID;
pStmt = conn.prepareStatement(sql2);
ResultSet rs2 = pStmt.executeQuery();
//check if QualificationsTable has content on that row...
if (rs2.next()) {
//it has content update...
//get the model for the qual table...
DefaultTableModel tModel = (DefaultTableModel) qualTable.getModel();
for (int i = 0; i < tModel.getRowCount(); i++) {
//get inputs from the tables
String qualification = tModel.getValueAt(i, 0).toString();
String yearAttained = tModel.getValueAt(i, 1).toString();
//sql query for updating qualifications table...
String sql3 = "update QualificationsTable set qualifications = ?, yearAttained = ? where qualID = ?";
pStmt = conn.prepareStatement(sql3);
//set the pareameters...
pStmt.setString(1, qualification);
pStmt.setString(2, yearAttained);
pStmt.setInt(3, theRowID);
//execute the prepared statement...
pStmt.execute();
// dbStatement.executeUpdate("INSERT INTO tableName VALUES('"+item+"','"+quant+"','"+unit+"','"+tot+"')");
}
//close connection
conn.close();
JOptionPane.showMessageDialog(null, "Qualifications updated successfully!", "Success", INFORMATION_MESSAGE);
} else {
//it doesnt have content insert...
//get the model for the qual table...
DefaultTableModel tModel = (DefaultTableModel) qualTable.getModel();
for (int i = 0; i < tModel.getRowCount(); i++) {
//System.out.println(tModel.getSelectedColumn()+tModel.getSelectedRow());
//get inputs from the tables
String qualification = tModel.getValueAt(i, 0).toString();
String yearAttained = tModel.getValueAt(i, 1).toString();
//sql query for storing into QualificationsTable
String sql3 = "insert into QualificationsTable (qualifications,yearAttained,qualID) "
+ "values (?,?,?)";
pStmt = conn.prepareStatement(sql3);
//set the parameters...
pStmt.setString(1, qualification);
pStmt.setString(2, yearAttained);
pStmt.setInt(3, theRowID);
//execute the prepared statement...
pStmt.execute();
}
//close connection
conn.close();
JOptionPane.showMessageDialog(null, "Qualifications saved successfully!", "Success", INFORMATION_MESSAGE);
}
} catch (SQLException ex) {
Logger.getLogger(StoreInfo.class.getName()).log(Level.SEVERE, null, ex);
} catch(NullPointerException nfe){
JOptionPane.showMessageDialog(infoParentTab, "Please, always hit the Enter button to effect your changes on the table", "USER ERROR!", ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(infoParentTab, "You must select a Staff from the Browser...", "USER ERROR!", ERROR_MESSAGE);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
what i am actually trying to do is to use a table linked to a database to store qualifications of staff in a company. now each entry in the qualifications database is referenced to the staffID in the staffs database through qualID.
so when i store the qualification on the table, it also records the staff that has the qualification. this should enable me retrieve a particular staff's qualifications from the database when need.
the segment for inserting into the database if empty works fine (i.e. the else... segment). but the update segment (i.e. the if... segment) is faulty in the sense that the code uses the last row on the JTable to populate all the rows in the database table instead of replicating all the new changes into the database table when update is need.
i have tried everything i could to no avail. please i need much help in this...time is not on my side. tnx guys in advance
The best way to do this is to use a CachedRowSet to back up the JTable's model. You'll be able to view, insert and update data easily.
Here's the tutorial: Using JDBC with GUI API

Query in a loop which is executed only once Java

I am currently working on a Java project (on NetBeans) and I am struggling with a problem.
In fact, I have a jTable which contains several elements, which element has a jCheckBox in the second column and I would like to make a query to add the selected element (selected by the jCheckBox of course) in a table.
I can get the data that I want to add, but my query works only once. I have already check my loop but I don't where the problem comes from.
I let you see the code :
try {
// Getting id of the selected value in the jComboBox
String idParcours = oParcoursDAO.findIdParcours(jComboBoxParcours.getSelectedItem().toString());
int id = Integer.parseInt(idParcours);
// for each value in the jTable
for(int i=0; i <jTable2.getRowCount(); i++){
boolean isChecked = (Boolean)jTable2.getValueAt(i, 1);
String nomPoi = (String)jTable2.getValueAt(i, 0);
// if the value is selected
if(isChecked){
String IDPoi = oParcoursDAO.findIdPoi(nomPoi);
int idpoi = Integer.parseInt(IDPoi);
System.out.println("idpoi "+idpoi); // It works I saw as idpoi as I have choose
System.out.println("id "+id) // It works too
oParcoursDAO.addPoi(idpoi,id); // it works only once
}
}
}catch (SQLException ex) {
Logger.getLogger(ModificationParcoursJInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Thank you in advance for your help.
This is my statement
public void addPoi(int idPoi,int idParcours) throws SQLException{
String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setInt(1,idPoi);
preparedStatement.setInt(2,idParcours);
preparedStatement.executeUpdate();
preparedStatement.close();
}
Why are you running one query per line? You can execute all of them in a single SQL using batch queries. It will require you to change the code but it will make it more efficient:
public void addPoi(Map<integer,Integer> poiMap) throws SQLException{
String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
PreparedStatement preparedStatement = conn.prepareStatement(query);
for(Integer idPoi:poiMap.keySet()) {
preparedStatement.setInt(1,idPoi);
preparedStatement.setInt(2,poiMap.get(idPoi));
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
preparedStatement.close();
}
Of course the original method has to be changed accordingly.

Categories