Could someone provide me with an example or tutorial on how to import a data from a mysql database within a JTable within the use of a GUI. I tried looking for an example but have not found anything.
Hopefully we can put this question to rest
Connection db = DriverManager.getConnection( jdbc:mysql://192.168.0.3:3306,<user>,<password>);
Statement stmt = db.createStatement();
PreparedStatement psmt = con.prepareStatement("SELECT * FROM DB");
ResultSet rs = psmt.executeQuery();
// get column names
int len = rs.getMetaData().getColumnCount();
Vector cols= new Vector(len);
for(int i=1; i<=len; i++) // Note starting at 1
cols.add(rs.getMetaData().getColumnName(i));
// Add Data
Vector data = new Vector();
while(rs.next())
{
Vector row; = new Vector(len);
for(int i=1; i<=len; i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
// Now create the table
JTable table = new JTable(data, cols);
Related
I have been developing small program in java, i made jtable and connect it to mysql, but it only shows 4 rows only no matter how big my data is...here is jtable in java
and here is mysql table data..
con = DBconnect.connect();
String[] columnNames = {"Name", "UserName", "UserType"};
model.setColumnIdentifiers(columnNames);
jTable1.setModel(model);
jTable1.setShowGrid(false);
try {
PreparedStatement pst;
pst = con.prepareStatement("select * from courses");
ResultSet rs = pst.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
int i = 0;
for(i = 0; i <= columns; i++){
if (rs.next()) {
uname = rs.getString("C_ID");
email = rs.getString("C_NAME");
pass = rs.getString("C_TYPE");
model.addRow(new Object[]{uname, email, pass});
}
}
You are mixing columns and rows, for(i = 0; i <= columns; i++) will only read 4 records/rows (because you have 3 columns) .
Simply browse the resultset with while(rs.next()) to get all the data :
while(rs.next()){
uname = rs.getString("C_ID");
email = rs.getString("C_NAME");
pass = rs.getString("C_TYPE");
model.addRow(new Object[]{uname, email, pass});
}
i have created jtable but it doesn't show the last column name i don't know what i did wrong in code database have 4 columns id , name, fathername and phone number but jtable only show 3 columns.
public void load() {
try {
DBO db = new DBO();
con = db.connect();
String sql = "Select * from personinfo";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
DefaultTableModel tb = new DefaultTableModel();
Vector col = new Vector();
for (int i = 1; i < count; i++) {
col.addElement(rsmd.getColumnName(i));
}
tb.setColumnIdentifiers(col);
while (rs.next()) {
Vector rows = new Vector();
for (int j = 1; j < rsmd.getColumnCount(); j++) {
rows.addElement(rs.getString(j));
}
tb.addRow(rows);
PersonTable.setModel(tb);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
I think you should use
pst.setString(1, "%"+name.getText()+"%");
when creating a prepared statement ? is used to replace bind variables. Values which you are not using as bind variables cannot be used the way you want, in this case using like. You can most probably go through this PreparedStatement IN clause alternatives?
Your question is quiet easily a duplicate Using “like” wildcard in prepared statement
I have a jTable with 4 columns and 6 rows. i want to iterate thru the rows picking up the values of column index0 which is my ID column and passing it to a count sql query. i have written the below code which is not working because i haven't figured out how to pass the columns values after iterating through the table.
can someone please let me know what am doing wrong on my code please.
for (int row = 0; row > jTable2.getRowCount(); row++){
for (int col =0; col > jTable2.getColumnCount(); col ++)
try{
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, col+1).toString();
String sql = "select COUNT(COURSEBOOKED) from APP.BOOKCOURSE where COURSEBOOKED = '"+selected+"'";
try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);) {
ResultSet rs = pst.executeQuery();
while(rs.next()){
String Sum = rs.getString("COUNT(COURSEBOOKED)");
System.out.println(Sum);
if (rs.wasNull()){
System.out.println("No record found");
}
}
}
catch(SQLException e){
}
}
catch(Exception e){
}
}
This is the final code that came up with after the changes.
String sql = "select COUNT(COURSEBOOKED) as count from APP.BOOKCOURSE where COURSEBOOKED =?";
try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
for(int row = 0; row < jTable2.getRowCount(); row++){
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, 1).toString();
pst.setString(1, selected);
try(ResultSet rs = pst.executeQuery();){
while (rs.next()){
String Sum = rs.getString("count");
System.out.println(Sum);
}
}
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(this, e);
}
Which brings me to my next question. AM not sure whether i should start a new thread for it or continue on this one. My challenge is that i now want to append an addition column to the existing 4 columns on the current jTable2 and display the values of the above query. to add a new column i have used this code,
TableColumn c = new TableColumn();
c.setHeaderValue("Training accomplished");
model.addColumn(c);
This adds the column but populates its with values from column index0. how do i get the new added column to be populated by the values held in Sum from the query above.
You should use something like below. Note that I haven't tested this code so far, so you might need to debug it. Also check the comments on your question.
String sql = "select COUNT(COURSEBOOKED) as count from APP.BOOKCOURSE where COURSEBOOKED = ?";
try(
Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
for (int row = 0; row < jTable2.getRowCount(); row++){
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, 0).toString();
pst.setString(1, selected);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String Sum = rs.getString("count");
System.out.println(Sum);
if (rs.wasNull()){
System.out.println("No record found");
}
}
}
}
catch(SQLException e){
}
catch(Exception e){
}
connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
table_1.setModel(buildTableModel(result));
method:
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
result:
You need to wrap your JTable inside a JScrollPane, and add the resulting JScrollPane to your layout.
The sample code you provided does not show how you're adding the JTable to the JPanel or JFrame of your application.
Found a solution:
I put a JScrollPane in jframe then use following code:
connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
JTable t=new JTable();
t.setModel(buildTableModel(result));
s1.setViewportView(t);
s1 is JScrollPane.
Output:
How to display ResultSet in JTable. i am using this code
String [] record= new
String[ColCount];
for (i=0; i<ColCount; i++)
{
record[i]=rset1.getString(i+1);
}
cell[i] = rset1.getString("loginname");
cell[i] = rset1.getString( "role");
System.out.println(cell[i][0]);
//ItemGroup = rset1.getString( "Status");
}
System.out.println(ItemCode);
JTable jt = new JTable(
cell[i], headers);
but I get only one row which is lastly inserted to database.
You need to put a while loop around your code to iterate over the result set. eg,
while(rset1.next())
{
//do something
}
The code that you have listed is incomplete/incomprehensible, but the code below shows how to take a ResultSet with an arbitrary number of columns and display its contents in a JTable.
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
private void viewTable(){
//Perform database query here, which will open a Connection to the database
//Assume we use the above query to populate a ResultSet results
//Get information about the ResultSet
ResultSetMetaData metaData = results.getMetaData();
//Gets the number of columns in results
int columnCount = metaData.getColumnCount();
//Gets the name of each column in results
String[] columnNames = new String[columnCount];
for(int i = 0; i < columnNames.length; i++){
columnNames[i] = metaData.getColumnLabel(i+1);
}
//You can use a String[] to keep track of the rows if you know the #
//# of rows in the ResultSet, this implementation assumes that we don't
//This ArrayList will keep track of each row in results (each row is
//represented by a String[]
ArrayList<String[]> rows = new ArrayList<>();
while(results.next()){
//Fetch each row from the ResultSet, and add to ArrayList of rows
String[] currentRow = new String[columnCount];
for(int i = 0; i < columnCount; i++){
//Again, note that ResultSet column indecies start at 1
currentRow[i] = results.getString(i+1);
}
rows.add(currentRow);
}
//Close Connection to the database here
String[][] rowsArray = new String[rows.size()][columnCount];
rowsArray = rows.toArray(rowsArray);
table = new JTable(rowsArray, columnNames);
}