Update one column from table and insert new rows. sqlite, java - 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();
}
}
}

Related

Problem with diacritic, getting data from database java

I have MySQL database, where I have saved data and some words have diacritics.
This is my function how to get data from database.
public List<RowType> getData(String query){
List<RowType> list = new ArrayList<>();
try{
connect();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()){
StringBuilder str = new StringBuilder();
for(int i = 1; i <= getCountColumns(resultSet); i++){
if(i==1) str.append(resultSet.getString(i));
else str.append("," + resultSet.getString(i));
}
list.add(new RowType(str.toString()));
}
}
catch(Exception e){
System.out.println("Chyba při získavání údajů z databáze.");
System.out.println(e);
Console.print("Chyba při získavání údajů z databáze.");
Console.print(e.toString());
}
finally{
disconnect();
}
return list;
}
As parameter i send this query.
List<RowType> list = connection.getData("Select id from countries where name = 'Česko'");
But it doesn´t find anything, because i have diacritic in the query ("Česko"). I try it without diacritic and it works. So don´t you know how to fix it to work with accents too?
Can you try to add a few more queries before executing your main query?
so it will look something like:
connect();
Statement statement = connection.createStatement();
String query2 = "SET NAMES 'utf8'";
statement.execute(query2);
query2 = "SET CHARACTER SET 'utf8'";
statement.execute(query2);
ResultSet resultSet = statement.executeQuery(query);
if the above does not work for you, then maybe there is an issue with your database settings; if that's the case, you can refer to the answer here

Data Added twice in to the database using JTable 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();

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

Getting next value from sequence

I have a bit of code here to get the next value of my sequence, but it is adding the total number of records onto the result each time.
I'm only learning about prepared Statements, I'm thinking this is something small, maybe rset.next() should be something else?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
Any help appreciated.
I think you don't need the call to pstmt.executeUpdate();
As stated in ResultSet doc, the function insertRow stores the row in the Dataset AND in the database.
The following code shows all that's necessary to add a new row:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
Why dont you iterate using while rather than if . something like this
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
Shouldn't you be doing this instead?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
As it is, it seems like you're passing a slightly bogus string into the SQL query, which is probably defaulting to the max index (not 100% positive on that). Then rs.next() is just incrementing that.

Store rows of resultset in array of strings

I want to count the numbers of entries in resultset and then store these values in an array and pass this array to create a graph.
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename"); // this statement will select the unique entries in a
particular column provided by jtextfield
int count=0;
while(rs.next())
{ ++count; } // This will count the number of entries in the result set.
Now I want to store the values of result set in an array of string. I used the following code
String[] row = new String[count];
while(rs.next())
{
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
}
Error : Invalid Descriptor Index.
Please suggest how to copy the result of resultset in array.
For example if I enter priority in jTextField , the result set will contain
priority1
priority2
priority3
In your first while loop you read all the entries in the ResultSet, so when executing the second while loop there's nothing else to read. Also, the index of ResultSet#getXxx starts at 1, not at 0. Also, since you don't know the amount of rows that you will read, it will be better using a List backed by ArrayList instead.
Considering these, your code should look like:
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+
" as call from tablename");
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
Based in your comment, I extended the sample:
public List<String> yourRandomQuery(String columnName) {
Connection con = null;
ResultSet rs = null;
List<String> results = new ArrayList<String>();
try {
String baseQuery = "SELECT DISTINCT %s AS call FROM tablename";
con = ...; //retrieve your connection
ResultSet rs = stmt.executeQuery(String.format(baseQuery, columnName));
while(rs.next()) {
results.add(rs.getString(1));
}
} catch (SQLException e) {
//handle your exception
e.printStacktrace(System.out);
} finally {
closeResource(rs);
closeResource(con);
}
return results;
}
//both Connection and ResultSet interfaces extends from AutoCloseable interface
public void closeResource(AutoCloseable ac) {
try {
if (ac != null) {
ac.close();
}
} catch (Exception e) {
//handle this exception as well...
}
}
public void someMethod() {
//retrieve the results from database
List<String> results = yourRandomQuery(jTextField.getText());
//consume the results as you wish
//basic example: printing them in the console
for(String result : results) {
System.out.println(result);
}
}
Try this
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename");
List<String> list=new ArrayList<>();
while(rs.next())
{
list.add(rs.getString(1));
}
Why not just create a HashSet<String> and write into that. Note that HashSet is unordered, just like your query. By using a collection that is of arbitrary size you don't need to determine the require dsize in advance.

Categories