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
Related
Here is code, i am using 2 jdatechooser and i put the codes in a button. I am also not sure if the query is correct.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://USER-PC:1433;databaseName=tblgg";
String userr="sa";
String passs="1234";
Connection con=DriverManager.getConnection(url,userr,passs);
java.util.Date first = dt1.getDate();
java.util.Date second = dt2.getDate();
String sql="SELECT * FROM tbl_sale WHERE date between '"+ first+"'and
'"+second+"'";
PreparedStatement pst= con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
tblsale.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Okay i edit my code. xD now something is happening but nothing is showing up.
To correct your lack of prepared statement usage. Try this
Resuse your connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://USER-PC:1433;databaseName=tblgg";
String userr="sa";
String passs="1234";
Connection con=DriverManager.getConnection(url,userr,passs);
ResultSet result = null;
String sql2 = "select\n" +
"*\n" +
"from student\n" +
"where date(first) > ? and date(second) < ?";
PreparedStatement ps1 = con.prepareStatement( sql2, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY) ;
ps1.setObject (1 , startDatePicker.getModel().getValue());
ps1.setObject (2 , endDatePicker.getModel().getValue());
result = ps1.executeQuery();
// get number of rows
result.last();
numRows = result.getRow();
result.first();
//Get metadata object for result
ResultSetMetaData meta = result.getMetaData();
// create an arry of string for the colum names
colNames = new String[meta.getColumnCount()];
// store column names in the new col names array
for( int i = 0; i< meta.getColumnCount(); i++)
{
//get column name
colNames[i] = meta.getColumnLabel(i+1);
}
// create 2 d string array for table data
tableData = new String [numRows][meta.getColumnCount()];
// store columns in the data
for ( int row = 0 ; row < numRows; row++)
{
for (int col = 0; col < meta.getColumnCount(); col++)
{
tableData[row][col]= result.getString(col + 1);
}
result.next();
}
// close statement
ps1.close();
connection.close();
System.out.println("Data Table Loaded.");
}
To show the created result data set you use these lines
JTable table = new JTable(tableData,colNames);
JScrollPane scrollPane = new JScrollPane(table);
Don't forget to add the scroll pane to your JPanel
panel.add(scrollPane);
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 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){
}
I need to fill a Swing table with some data from MySQL DB. The problem is that the table does not display all the columns (i.e. a.aircraftType and b.aircraftCategory). In Debug mode I checked that the query returns correct data. So, why finally some columns are not displayed?
private JTable tbArrivals;
private QueryTableModelFS mdArrivals;
mdArrivals = new QueryTableModelFS();
tbArrivals = new JTable(mdArrivals);
private void fillArrivals() {
mdArrivals.setHost(url); mdArrivals.setDB(db); mdArrivals.setLogin(login); mdArrivals.setPassw(passw);
String query;
query = "SELECT a.id,a.flightNum_arr,a.from_ICAO,a.ETA,a.pkId,a.aircraftType,b.aircraftCategory " +
"FROM flightschedule a, aircrafts b " +
"WHERE a.aircraftType = b.aircraftType;";
mdArrivals.setQuery(query);
}
public void setQuery(String query) {
cache = new Vector();
try {
// Execute the query and store the result set and its metadata
Connection con = getConnection();
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
// Rebuild the headers array with the new column names
headers = new String[colCount];
for (int h = 1; h <= colCount; h++) {
headers[h - 1] = meta.getColumnName(h);
}
while (rs.next()) {
String[] record = new String[colCount];
for (int i = 0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
}
cache.addElement(record);
}
fireTableChanged(null);
rs.close();
if (con.getAutoCommit() != false) {
con.close();
}
} catch (Exception e) {
cache = new Vector();
e.printStackTrace();
}
}
I can't tell what how your TableModel works (it looks like you might be using the DefaultTableModel), but I would suggest using Vectors instead of Arrays to get the data from your ResultSet. Right now your code is very confusing. In one loop you are using (i - 1) to access the data. In the next loop you are using (i + 1). I know the reason is because Arrays are 0 based and the ResultSet is 1 based.
When you use a Vector your loops can just start with 1 and then you just use the addElement() method to add the data to the Vector so your code is not concerned with matching indexes.
See Table From Database Example in Table From Database.
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);