I want to be able to select any row, just 1 row specifically and edit its data.
The data is in a SQL Table.
I am using tableview with scenebuilder 2.
The Problem: The row I select does not update with new fields. Not sure If it recognizes the selection.
Code is posted Below
Sorry if I am not being fully clear, I will be happy to explain further if needed
Connection c;
data = FXCollections.observableArrayList();
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
//We are using non property style for making dynamic table
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
tableview.getColumns().addAll(col);
System.out.println("Column [" + i + "] ");
}
/********************************
* Data added to ObservableList *
********************************/
while (rs.next()) {
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
//Iterate Column
row.add(rs.getString(i));
}
System.out.println("Row [1] added " + row);
data.add(row);
}
//FINALLY ADDED TO TableView
tableview.setItems(data);
c.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
////SELECT A ROW AND EDIT
String a =(String)tableview.getSelectionModel().getSelectedCells().toString();
String query = "UPDATE Frontdesk SET CustomerName = ? , Zip = ? , Make =? , Model=? , PhoneNumber =? WHERE CustomerName =? ";
PreparedStatement preparedStmt = c.prepareStatement(query);
preparedStmt.setString(1, txtCus);
preparedStmt.setString(2, txtzi);
preparedStmt.setString(3, txtMod);
preparedStmt.setString(4, txtMak);
preparedStmt.setString(5, txtPun);
preparedStmt.setString(6, a);
preparedStmt.executeUpdate();
This is a screenshot of the application:
Related
When a user clicks a button initially, a query is run and each row is put into a JPanel and added to the display for the user to view. Which works fine.
My problem is, I want the user to be able to filter these results according to values that they provide ( through a JTextField ) , and I want the displayed records to update as the value of the JTextField changes. My queries are formed and executed each time the JTextField is changed, but I can't find a way to update the records displayed.
Any help would be appreciated.
The code took a while to edit to the satisfaction of stackoverflow, but here it is. Hopefully you can follow the logic. This is the method that deals with formation and execution of the queries, which works(again).
The problem is displaying the new results.
private void processSearch(){
int count = 0;
double width;
remove(allInfo);
allInfo = new JPanel();
allInfo.setLayout(new GridLayout(0, 1, 5, 10));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
width = screenSize.getWidth();
try {
DatabaseConnetor connect = new DatabaseConnetor();
Connection conn = connect.connect();
String query = "";
String whereClause = "";
int unEmpty = 0;
String [] searches ={searchNameTxt.getText(), searchMailTxt.getText(), searchContactTxt.getText(), (String) searchGender.getSelectedItem()};
String [][] keys = {{"first_name", "middle_name", "family_name", "surname"}, {"email"}, {"contact", "contact2"}, {"gender"}};
for(int i=0; i < searches.length; i++){
if(!searches[i].trim().isEmpty()){
unEmpty++;
}
for(int i=0; i < searches.length; i++){
int counter = 0;
if(!searches[i].trim().isEmpty()){
whereClause += " AND ";
int len = keys[i].length;
if(len == 1){
whereClause += " ("+keys[i][0]+" LIKE '%"+searches[i]+"%') ";
}else if(len > 1){
whereClause += " ( ";
while(counter < len){
if(counter == len-1)
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%'";
else
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%' OR ";
counter++;
}
whereClause += " ) ";
}
}
}
query = "SELECT photo, first_name, middle_name, family_name, surname, gender, email, contact, contact2 FROM user WHERE rights = 2" + whereClause;
PreparedStatement preparedStatement = conn.prepareStatement(query);
String gen = "", middle = "", family = "", cont = "", phot = "";
ResultSet result = preparedStatement.executeQuery();
while(result.next()){
JPanel data = new JPanel();
data.setPreferredSize(new Dimension((int)(width*0.75), 50));
data.setLayout(new GridLayout(1, 0, 5, 10));
if(result.getString(1) == "NULL")
phot = "";
data.add(new JLabel(phot)); //Photo
data.add(new JLabel(result.getString(2))); //First Name
if(result.getString(3) == "NULL")
middle = "";
data.add(new JLabel(middle)); //Middle Name
if(result.getString(4) == "NULL")
family = "";
data.add(new JLabel(family)); //Family Name
data.add(new JLabel(result.getString(5))); //Surname
if(result.getString(6).equals("M"))
gen = "Male";
else
gen = "Female";
data.add(new JLabel(gen)); //Gender
data.add(new JLabel(result.getString(7))); //E-Mail
data.add(new JLabel(result.getString(8))); //Contact1
if(result.getString(9) == "NULL")
cont = "";
data.add(new JLabel(cont)); //Contact 2
allInfo.add(data);
}
add(allInfo);
connect.disconnect(conn);
connect = null;
conn = null;
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
a query is run and each row is put into a JPanel and added to the display for the user to view
I would suggest you use a JTable to display the data from a database. A JTable is designed to display data in a row/column format.
Read the section from the Swing tutorial on How to Use Tables for more information and examples.
I want the user to be able to filter these results according to values that they provide ( through a JTextField ) , and I want the displayed records to update as the value of the JTextField changes.
A JTable supports dynamic filtering of the data displayed in the table. The above tutorial has a section on Sorting and Filtering that shows how to filter as text is entered into a text field. Filtering the table is more efficient then redoing the SQL query.
Adding data to the table is straight forward. Instead of creating a panel with each column of data you can add a new row of data to the TableModel:
String sql = "Select * from ???";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
#Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JTable table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );
I coded Auto Suggesting Combo boxes. Functionality is,
*when a user type the first letter in either combo box , data retrieves from the MySQL database and show in a popup list, when a user click on a suggested item ,then press Add button that item added to the J Table and clears the combo boxes
But when I select another item from the combo box and click Add button before added one disappears
*How can I keep Both or many items in the J Table according to above situation *
I'll post my code:
private void NamecomboActionPerformed(java.awt.event.ActionEvent evt) {
String drugname = (String) Namecombo.getSelectedItem();
try{
String name = "SELECT * FROM druginfo WHERE ItemName LIKE '"+drugname+"%'";
PreparedStatement pstmt = conn.prepareStatement(name);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
IDcombo.setSelectedItem(rs.getString("ItemID"));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"error "+ e);
}
}
private void IDcomboActionPerformed(java.awt.event.ActionEvent evt) {
String drugid = (String) IDcombo.getSelectedItem();
try{
String name = "SELECT * FROM druginfo WHERE ItemID LIKE '"+drugid+"%'";
PreparedStatement pstmt = conn.prepareStatement(name);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
Namecombo.setSelectedItem(rs.getString("ItemName"));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"error "+ e);
}
try{
String exp = "SELECT ExpDate FROM druginfo WHERE ItemID LIKE '"+drugid+"%'";
PreparedStatement pstmt = conn.prepareStatement(exp);
ResultSet rs2 = pstmt.executeQuery();
while (rs2.next()){
String date = rs2.getString("ExpDate");
exptxt.setText(date);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"error "+ e);
}
}
add button action performed for adding item to JTable;
private void add_btnActionPerformed(java.awt.event.ActionEvent evt) {
String temp = (String) IDcombo.getSelectedItem();
String sql = "select ItemID,ItemName,CostPrice,InStock from druginfo where ItemID=?";
try {
pst=conn.prepareStatement(sql);
pst.setString(1, temp);
rs=pst.executeQuery();
tableSale.setModel(DbUtils.resultSetToTableModel(rs));
IDcombo.setSelectedItem(null);
Namecombo.setSelectedItem(null);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
Add the current selection(resultset data) to JTable object without replacing the old data.
rs=pst.executeQuery();
addDataToTable(tableSale,DbUtils.resultSetToTableModel(rs));
IDcombo.setSelectedItem(null);
Namecombo.setSelectedItem(null);
//ADD this method
public void addDataToTable(JTable table,TableModel model) {
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
DefaultTableModel resultSetModel = (DefaultTableModel) model;
for (int i = 0; i < resultSetModel.getRowCount(); i++) {
Vector row=new Vector();
for (int j = 0; j < resultSetModel.getColumnCount(); j++) {
row.addElement(resultSetModel.getValueAt(i, j));
}
tableModel.addRow(row);
}
tableModel.fireTableDataChanged();
}
This tableSale.setModel(DbUtils.resultSetToTableModel(rs)); will replace the old model with new model.So obviously datas will be lost.You have to add values to the existing model.I have added a snippet which will help you.
Replace tableSale.setModel(DbUtils.resultSetToTableModel(rs)); with addValuesToModel(DbUtils.resultSetToTableModel(rs));
addValuesToModel(DbUtils.resultSetToTableModel(rs));
public void addValuesToModel(TableModel resultModel) {
DefaultTableModel tmodel = (DefaultTableModel) tableSale.getModel();
DefaultTableModel rmodel = (DefaultTableModel) resultModel;
for (int i = 0; i < rmodel.getRowCount(); i++) {
Object[] row = new Object[rmodel.getColumnCount()];
for (int j = 0; j < rmodel.getColumnCount(); j++) {
row[j] = rmodel.getValueAt(i, j);
}
tmodel.addRow(row);
}
}
public cntctus()
{
column names for JTable
String column[]= { "Name","Position","Phone"};
rows for JTable
Object [][]row = {
{"Prof. Renu Vig", "Director", "+123456"},
{"Mr. Sukhbir singh", "Assistant Professor", "+9123568989"},
{"Ms. shaweta", "BI teacher","9468645"}
};
table = new JTable(row,column);
TableModel tm = table.getModel();
java.sql.Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/training","root","");
try{
java.sql.Statement stmt =con.createStatement();
String maketable = "CREATE TABLE if not exists contacttable(Name Varchar(25),Position Varchar(20),Phone Varchar(20))";
stmt.executeUpdate(maketable);
System.out.print("table created ");
//insert into table contacttable query
PreparedStatement pstmt=con.prepareStatement("INSERT into contacttable select distinct values(?,?,?)");
get some TableModel that will contain the data
for (int i = 0; i < tm.getRowCount(); i++) {
for (int j = 0; j < tm.getColumnCount(); j++) {
Object o = tm.getValueAt(i, j);
System.out.println("object from table is : " +o);
k=j+1;
pstmt.setString(k, (String)o);
}
pstmt.executeUpdate();
}
}
catch(SQLException s)
{
System.out.println(s);
}
}
catch(Exception e)
{
e.printStackTrace();
}
I want to insert this whole object into database.in short how to insert jtable data into databse.?? please help.
error is: you have an error in your sql syntax at line 1 ('"prof. renu vig, "director"...
In the event that you want to have multiple rows on your prepared statement, you could just take what you have now and add a call to pstmt.addBatch() inside the outer loop, and outside the inner loop (the loops which iterate over the JTable, IE add batch once per row). Then after you have iterated over the whole table call pstmt.executeBatch().
A word to the wise though, if you are generating keys on insert, the drivers must also support returning multiple keys on batch inserts, or you will probably just get the first key generated back instead of all of them. Alternatively you could execute the statement each iteration of the outer loop (IE once per row), making sure to call .clearParamters() after each execution. You will want to reuse the preparedStatement for performance reasons.
Your insert statement is also screwed up. Its just going to be INSERT INTO contacttable VALUES(?,?,?). Get rid of the select distinct stuff.
It will probably look like this when its done:
String column[]= { "Name","Position","Phone"};
Object [][]row = {
{"Prof. Renu Vig", "Director", "+123456"},
{"Mr. Sukhbir singh", "Assistant Professor", "+9123568989"},
{"Ms. shaweta", "BI teacher","9468645"}
};
JTable table = new JTable(row,column);
TableModel tm = table.getModel();
java.sql.Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/training","root","");
java.sql.Statement stmt =con.createStatement();
String maketable = "CREATE TABLE if not exists contacttable(Name Varchar(25),Position Varchar(20),Phone Varchar(20))";
stmt.executeUpdate(maketable);
System.out.print("table created ");
PreparedStatement pstmt=con.prepareStatement("INSERT INTO contacttable VALUES(?,?,?)");
for (int i = 0; i < tm.getRowCount(); i++) {
for (int j = 0; j < tm.getColumnCount(); j++) {
Object o = tm.getValueAt(i, j);
System.out.println("object from table is : " +o);
pstmt.setString(j+1, (String)o);
}
pstmt.executeUpdate();
pstmt.clearParameters();
}
}
catch (Exception e) {
e.printStackTrace();
}
The Only one change You have to do with your Code i.e
for (int i = 0; i < tm.getRowCount(); i++) {
for (int j = 0; j < tm.getColumnCount(); j++) {
Object o = tm.getValueAt(i, j);
System.out.println("object from table is : " +o);
pstmt.setObject(j+1, o);
it will send your actual JTable data into your Database file.
i am sure. it will work work.
i have an exemple with jpa i hope that it help you
try{
TableModel tm= table.getModel();
for (int i = 0; i < tm.getRowCount(); i++) {
Object NumeroCin=tm.getValueAt(i, 0);
Object Nomprenom=tm.getValueAt(i, 1);
Object Tel =tm.getValueAt(i, 2);
Object Adresse =tm.getValueAt(i, 3);
Object DateNaissance=tm.getValueAt(i, 5);
Object Sexe=tm.getValueAt(i, 4);
Etudiant e=new Etudiant();
e.setAdresse((String) Adresse);
e.setDateNaissance((String) DateNaissance);
e.setNomprenom((String) Nomprenom);
e.setNumeroCin((String) NumeroCin);
e.setSexe( (String) Sexe );
e.setTel((String) Tel);
Ajouterobjet(e);
}}}
catch (Exception e) {
e.printStackTrace();
}
public void Ajouterobjet(Object o)
{
EntityTransaction tx=entityManager.getTransaction();
tx.begin();
entityManager.persist(o);
tx.commit();
}
I'm currently scraping some scores from a HTML page and then inputting them into a SQL database.
The scores are being parsed using Jsoup into an ArrayList. From here I'm converting the ArrayList to a String to allow it to be parsed into a VARCHAR field in the db. Although I can't seem to work out how to edit the for loop I have to insert all the values at once.
Here is my current code:
Document doc = Jsoup.connect(URL).timeout(5000).get();
for (Element table : doc.select("table:first-of-type")) //selects first table
{
for (Element row : table.select("tr:gt(0)")) { //selects first table cell
Elements tds = row.select("td");//selects row
List1.add(tds.get(0).text());
List2.add(tds.get(1).text());
List3.add(tds.get(2).text());
}
}
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Scores (Home, Score, Away) VALUES (?,?,?)");
String[] List1str = new String[List1.size()];
List1str = List1.toArray(List1str);
for (String s : List1str) {
stmt.setString(1, s);
stmt.setString(2, "test");
stmt.setString(3, "test");
stmt.executeUpdate();
}
for (int i = 0; i < dtm.getRowCount(); i++) {
for (int j = 0; j < dtm.getColumnCount(); j++) {
Object o = dtm.getValueAt(i, j);
System.out.println("object from table is : " + o);
pst.setString(j + 1, (String) o);
}
pst.executeUpdate();
pst.clearParameters();
}
This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 8 years ago.
Hello I'm trying to make an error when there is no matched student...
and it will display like this
No matching records found and I want the column name still the same but still not figuring it out... can some one tell me if this is right??
Heres my function for that... and I add comment there where I put the error... but i don't know how to get the columnname
public void SearchTableStudent() {
String tempSearchValue = searchStudent.getText().trim();
boolean empty = true;
sql = "SELECT student_id as 'Student ID',"
+ "concat(lastname, ' , ', firstname, ' ', middlename) as 'Name'"
+ "FROM user "
+ "WHERE CAST(student_id as CHAR) LIKE '%" + tempSearchValue + "%'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
table.setModel(DbUtils.resultSetToTableModel(rs));
empty = false;
}
if(empty) {
String error = "";
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"No matching records found",null}
},
new String [] {
/** I WANT TO PUT THE SAME COLUMN NAME ON MY DATABASE SELECTED BUT DON't Know
WHAT FUNCTION TO DO*/
}
));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
I try like this but still gave me NULL!!!
this code is below of empty = false;
for(int i=0; i<table.getColumnCount(); i++) {
test[i] = table.getColumnName(i);
}
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
columnName[i-1] = metaData.getColumnLabel(i);
System.out.println(columnName[i-1]);
}
Try this.
ResultSetMetaData meta = resultset.getMetaData();
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = new String[columncount];
while(count<=columncount){
columnNames [count-1] = meta.getColumnLabel(count);
count++;
}
Since here your expecting is to get the columns alias instead of column name, so you have to use ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.
Get ResultSetMetaData using ResultSet#getMetaData():
ResultSetMetaData meta = rs.getMetaData();
And then to get column name of 1st column:
String col1Name = meta.getColumnLabel(1);
Similarly to get column name of 2nd column:
String col2Name = meta.getColumnLabel(2);
Get the metadata
ResultSetMetaData metaData = rs.getMetaData();
Then you can do:
String columnName = metaData.getColumnName(int index);
ResultSetMetaData doc
rs.getMetaData().getColumnName(int i);
and do not concat the query param!