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);
Related
When I am typing in jtable row I need to get suggestions to that table rows(filtered) from mysql data base and select from it (like Invoice generating as picture )I need to develop as below picture and here is the code I coded so far
jdbc j = new jdbc();
DefaultTableModel dt = (DefaultTableModel) tab_reta_in.getModel();
int row = tab_reta_in.getSelectedRow();
int col = tab_reta_in.getSelectedColumn();
Data_feild = (String) tab_reta_in.getValueAt(row, col);
int Def_r = row;
if (col == 0) {
try {
ResultSet rs = j.GetData("select * from invoice_retails where name like '" + Data_feild + "%' ");
while (rs.next()) {
String col0 = rs.getString("medi_id");
String col1 = rs.getString("name");
String col2 = rs.getString("prize");
Object[] rows = {col0, col1, col2};
dt.addRow(rows);
}
} catch (Exception ex) {
System.out.println(ex);
}
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){
}
I am using PhpMyAdmin to save my data in database. I have a SWT table to populate with database content.
here is my code..
public static void fetchDatafromDB(String StartIndex, String FinalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `From`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + StartIndex + "' AND '" + FinalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
// System.out.print(rs.getString(i));
item.setText(i, rs.getString(i));
}
// System.out.println();
}
} catch (Exception P) {
P.printStackTrace();
}
}
it worked.
Now I am getting some problem with tabling the DB content in my swt table. What my program does, is that, it sets the selected (defined by limit in program above) content of DB in one row (one by one manner) but I want the next row of DB table to be tabled in next row of SWT table. Could you suggest something about this? ! Screenshot of my swtTable
It should look something like this:
public static void fetchDatafromDB(String startIndex, String finalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `FROM`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + startIndex + "' AND '" + finalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
TableItem item;
while (rs.next()) {
// Create a new TableItem for each entry in the result set (each row)
item = new TableItem(table, SWT.NONE);
for (int i = 1; i <= columnsNumber; i++) {
// Populate the item (mind the index!!)
item.setText(i - 1, rs.getString(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
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.