java - jTable database repeating values - java

I am trying to populate a java database with car brands, models, and if they are available but I have a big issue. When I enter multiple cars to the table, the new car prints to the table, but previous cars I have entered also reprint
[Issue.png][1]. So first I entered Ferrari Enzo, then I entered Tesla S but Ferrari Enzo is repeating.
I know the issue is not with adding the cars to the database because if I look in the database it only shows the two I entered [DatabasePic.png][2]. I know my problem is with how I am entering my cars into the JTable. My methods are below..
ButtonClickEvent:
private void refreshbtnMouseClicked(java.awt.event.MouseEvent evt) {
try {
String Brand = brandlbl.getText();
String Model = modellbl.getText();
Boolean Available = false;
switch (availabilitybox.getSelectedItem().toString()) {
case "True":
Available = true;
break;
case "False":
Available = false;
break;
}
InsertApp nw = new InsertApp();
nw.insert(Brand, Model, Available);
nw.refreshDatabase(jTable1);
} catch (SQLException ex) {
Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
Insert Method:
public void insert(String brand, String model, Boolean available) {
String sql = "INSERT INTO CARDATA(brand,model,available) VALUES(?,?,?)";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, brand);
pstmt.setString(2, model);
pstmt.setBoolean(3, available);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
Refreshing my database:
public void refreshDatabase(JTable table) throws SQLException {
Connection con = connect();
String SQL = "SELECT * FROM CARDATA";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
int col = rs.getMetaData().getColumnCount();
System.out.println(col);
while (rs.next()) {
Object[] rows = new Object[col];
for (int i = 1; i <= col; i++) {
rows[i - 1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, rows);
}
con.close();
rs.close();
stmt.close();
}

When I enter multiple cars to the table, the new car prints to the table, but previous cars I have entered also reprint
You need to clear the data in the TableModel before you start adding data back into it.
The basic code should be something like:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.setRowCount(0);
while (rs.next())
{
...
model.addRow(...);
}
Or instead of retrieving all the data from the database every time you do an insert, just add the data to the table at the same time:
pstmt.executeUpdate();
model.addRow(...);

Related

Populate jtable from multiple MS Access databases

I successfully managed to populate jtable from an MS Access database using UcanAccess library.
What I want is to populate jtable from two databases. I have two databases, one contains table with four columns, the other contain three columns.
I want to populate jtable with seven columns from the two databases.
Code used :
public void PopulateJtable(JTable table, String table_name) {
String sql = "SELECT * from " + table_name;
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
dtm.setRowCount(0);
try {
conn = DriverManager.getConnection(myDB);
state = conn.createStatement();
state.execute(sql);
ResultSet rs = state.getResultSet();
int columns = table.getColumnCount();
Vector vector = new Vector();
while (rs.next()) {
Vector row = new Vector();
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
dtm.addRow(row);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e, "ERROR !! ", 0);
} finally {
try {
state.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBEngine.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
MS Access DB Tables :
table1
table2
i want to join above tables cols in one jtable

How to make one mySQL's table column invisible

I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";

Receiving all columns with StringBuilder

I've written a method that performs the following commands: select, insert, update, delete. Originally, I only wanted the first two columns of output after running SELECT * FROM SithLords. How can I get all of the rows and columns? Also, how can I allow the user to add newlines when running the select command like this:
SELECT jedi_name
FROM SithLords
WHERE level = 'master';
As of now, it only executes with one line:
select jedi_name from SithLords where level = 'master';
Code:
public void actionPerformed(ActionEvent e) {
String query = queryStatements.getText();
try {
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(query);
if(query.matches("(select|SELECT).*")) {
ResultSet result = stmt.executeQuery();
StringBuilder strResult = new StringBuilder();
while(result.next()) {
strResult.append(result.getString(1)).append(" ").append(result.getString(2));
strResult.append("\n");
}
queryResults.setText(strResult.toString());
} else if(query.matches("(insert|INSERT).*")) {
stmt.executeUpdate(query);
} else if(query.matches("(update|UPDATE).*")) {
stmt.executeUpdate(query);
} else if(query.matches("(delete|DELETE).*")) {
stmt.executeUpdate(query);
} else {
System.out.println("Not supported yet!");
}
} catch (SQLException error) {
error.printStackTrace();
}
}
If what you want is to retrieve from the recorset all its columns you could ask it how many columns does it have (n) and access from 1 to n:
ResultSet result = stmt.executeQuery();
ResultSetMetaData md = result.getMetaData();
int nCols = md.getColumnCount();
for(int c = 1; c <= nCols; c++)
strResult.append(result.getString(c).append(" "));
Concerning your multiline commands, you could replace the command end of lines by spaces:
query.replaceAll("(\\r|\\n)", " ");

Remove JTable row without convert RowIndex To Model

I know that for remove a row i should do this:
if (table.getSelectedRow() > -1) {
int rowToTable = table.getSelectedRow();
int rowToModel = table.convertRowIndexToModel(rowToTable);
model.removeBook(rowToModel);
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
But, Now i try this method without rowToModel variable and still remove correctly:
if (table.getSelectedRow() > -1) {
int rowToTable = table.getSelectedRow();
model.removeBook(rowToTable);
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
My removeBook() method:
public void removeBook(int row) {
Connection connection;
PreparedStatement preparedStatement;
String query = "Delete from BookTable where id=?";
try {
connection = DriverManager.getConnection(...);
Object id = this.getValueAt(row, 0);
preparedStatement = connection.prepareStatement(query);
preparedStatement.setObject(1, id);
if (preparedStatement.executeUpdate() == 1) {
this.removeRow(row);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
Why both of this works?!
And which is correct?
it works without conversion only if the table is neither sorted nor filtered - as your code can't know whether it is, it must convert the row index always. BTW, same for column index, as the user might have moved the column

Inserting information from one mysql table to another

I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}
You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.
I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.
With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;

Categories

Resources