HSQLDB Subquery - Java - java

In Microsoft Access I have three queries that work -
qryAwayMatches:
SELECT MatchTeam.FootballMatchID, MatchTeam.TeamID, MatchTeam.GameType, MatchProtocol.MatchTeamID, MatchProtocol.GoalNumber, MatchProtocol.YellowCardNumber, MatchProtocol.RedCardNumber
FROM MatchTeam LEFT JOIN MatchProtocol ON MatchTeam.ID = MatchProtocol.MatchTeamID
WHERE (((MatchTeam.GameType)="Away"));
qryHomeMatches:
SELECT MatchTeam.FootballMatchID, MatchTeam.TeamID, MatchTeam.GameType, MatchProtocol.MatchTeamID, MatchProtocol.GoalNumber, MatchProtocol.YellowCardNumber, MatchProtocol.RedCardNumber
FROM MatchTeam LEFT JOIN MatchProtocol ON MatchTeam.ID = MatchProtocol.MatchTeamID
WHERE (((MatchTeam.GameType)="Home"));
qryMatchResult:
SELECT qryHomeMatches.FootballMatchID, qryHomeMatches.TeamID AS HomeTeamID, qryAwayMatches.TeamID AS AwayTeamID, qryHomeMatches.GoalNumber AS HomeTeamGoals, qryAwayMatches.GoalNumber AS AwayTeamGoals, [HomeTeamGoals]>[AwayTeamGoals] AS HomeTeamWin, [HomeTeamGoals]=[AwayTeamGoals] AS NoWin, [HomeTeamGoals]<[AwayTeamGoals] AS AwayTeamWin
FROM qryHomeMatches INNER JOIN qryAwayMatches ON qryHomeMatches.FootballMatchID = qryAwayMatches.FootballMatchID;
In my Java program, I show the result of the first two queries on a button press in the following way:
btnqryAwayMatches.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String s;
JFrame frame;
String url = "jdbc:hsqldb:file:db_data/myFootballDB;ifexists=true;shutdown=true";
String username = "SA";
String password = "";
try {
con = DriverManager.getConnection(url, username, password);
st = con.createStatement();
s = "SELECT MATCHTEAM.FOOTBALLMATCHID, MATCHTEAM.TEAMID, MATCHTEAM.GAMETYPE, "
+ "MATCHPROTOCOL.MATCHTEAMID, MATCHPROTOCOL.GOALNUMBER, "
+ "MATCHPROTOCOL.YELLOWCARDNUMBER, "
+ "MATCHPROTOCOL.REDCARDNUMBER "
+ "FROM MATCHTEAM LEFT JOIN MATCHPROTOCOL ON MATCHTEAM.ID = MATCHPROTOCOL.MATCHTEAMID "
+ "WHERE (((MATCHTEAM.GAMETYPE)='Away'));";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
int c = rsmt.getColumnCount();
Vector<String> column = new Vector<String>(c);
for (int i = 1; i <= c; i++) {
column.add(rsmt.getColumnName(i));
}
Vector<Vector<String>> data = new Vector<Vector<String>>();
Vector<String> row = new Vector<String>();
while (rs.next()) {
row = new Vector<String>(c);
for(int i = 1; i <= c; i++) {
row.add(rs.getString(i));
}
data.add(row);
}
frame = new JFrame();
frame.setTitle("Away Match Results");
frame.setSize(700,420);
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data, column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
} catch(Exception exc) {
exc.printStackTrace();
JOptionPane.showMessageDialog(null, "Error");
} finally {
try {
st.close();
rs.close();
con.close();
} catch(Exception exception) {
JOptionPane.showMessageDialog(null, "Error close");
}
}
}
});
How can I code the third query to execute on a button click? I understand that it needs to know the result of the first two queries to execute, so I am not sure to how to program this.

You can do it easily with the WITH clause:
WITH qryAwayMatches AS (SELECT MatchTeam.FootballMatchID, ...),
qryHomeMatches AS (SELECT MatchTeam.FootballMatchID, ...)
SELECT qryHomeMatches.FootballMatchID, ...
Put the full text of each of the queries in the template above.

Related

Why can I only get one record from my table?

I am searching record from table using Employee_id, the same Employee_id has two records in table on same date but getting only one after searching record according to Employee_id.
I have the following columns in my table:
Device_ID, Employee_id, Employee_Name, Employee_Ext, Issue_Date
Here is my Java code:
public void actionPerformed(ActionEvent ae) {
try {
String str = tf5.getText();
Connection con = DB.getConnection();
PreparedStatement st = con.prepareStatement("select * from issuedevices where Employee_id=?");
st.setString(1, str);
ResultSet rs = st.executeQuery();
// Vector v = new Vector();
if (rs.next()) {
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
// from = (String) c1.getSelectedItem();
String id = "";
String Device_ID = "";
String Employee_id = "";
String Employee_Name = "";
String Employee_Ext = "";
String Issue_Date = "";
try {
pst = con.prepareStatement("select * from issuedevices where Employee_id='" + str + "'");
ResultSet rs1 = pst.executeQuery();
int i = 0;
if (rs1.next()) {
id = rs1.getString("id");
Device_ID = rs1.getString("Device_ID");
Employee_id = rs1.getString("Employee_id");
Employee_Name = rs1.getString("Employee_Name");
Employee_Ext = rs1.getString("Employee_Ext");
Issue_Date = rs1.getString("Issue_Date");
model.addRow(new Object[] {
id,
Device_ID,
Employee_id,
Employee_Name,
Employee_Ext,
Issue_Date
});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400, 300);
}
// st.close();
// rs.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Name not Found");
}
}
You have no loop so you only get one result. Try changing
if (rs1.next())
to
while (rs1.next())

Binding jtable from mysql database in netbeans

I have almost finished my project and I'm getting stuck with displaying the Data from my DB into a Jtable. I have searched and read and still can't get this to work. I'm not displaying any errors but when I run the code I get an error when I click on search for the data. I get
java.sql.SyntaxErrorException: Syntax error: Encountered "INVENTORY"
at line 1, column 9. Does that mean my code is fine and its a problem with my Database?
Here is my code.
private void cmdSEARCHINVActionPerformed(java.awt.event.ActionEvent evt) {
ResultSet rs = null;
try {
String host = "jdbc:derby://localhost:1527/The_Home_Place";
String uName = "Lynn";
String uPass = "Lynn";
Connection con = DriverManager.getConnection( host, uName, uPass );
Statement stmt = con.createStatement();
String Query = "SELECT *INVENTORY";
rs = stmt.executeQuery(Query);
ResultSetMetaData rsmt = rs.getMetaData();
int col = rsmt.getColumnCount();
Vector column = new Vector(col);
for(int i = 1; i <= col; i++)
{
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (rs.next());
{
row = new Vector(col);
for(int i = 1; i <= col; i++){
row.add(rs.getString(i));
}
data.add(row);
}
//Create the Table
JFrame frame = new JFrame();
frame.setSize(500,120);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data,column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp,BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}
Your SQL query has invalid syntax. Try changing it to
String query = "SELECT * FROM INVENTORY";
instead. Also, you shouldn't be using Vector anymore, because the class is obsolete; use an ArrayList<String> (a generic collection, not a raw one) for storing the row data instead.

Java JTable not showing the records

I am trying to get the records from Hive into JTable in a new frame.The new frame pops up with Column names but the records are not visible.Here is my code.
try{
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", "");
Statement stmt = con.createStatement();
ResultSet res;
stmt.setMaxRows(val);
sql = "select * from default.recommendations where recommendations.item='" + user +"'";
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(res.getString(1) + "\t" + res.getString(2) + "\t" + res.getString(3));
}
ResultSetMetaData rsmt = res.getMetaData();
int c = rsmt.getColumnCount();
Vector column = new Vector(c);
for(int i=1; i<=c; i++){
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (res.next()) {
row = new Vector(c);
for(int i=1; i<=c; i++){
row.add(res.getString(i));
}
data.add(row);
}
JFrame frame = new JFrame();
frame.setSize(500, 120);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data,column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp,BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
} catch(SQLException se){
System.Out.Println(se.getMessage())}
while (res.next())
{
System.out.println(res.getString(1) + "\t" + res.getString(2) + "\t" + res.getString(3));
}
After doing the query you read all the data and display it on the console.
while (res.next()) {
row = new Vector(c);
for(int i=1; i<=c; i++){
row.add(res.getString(i));
}
data.add(row);
}
Then later you try to read the data into the Vectors. Problem is that there is no data in the ResultSet because you have already read all the data.
Get rid of the first loop.
If you want to see the values of the ResultSet then put the System.out.println(...) statement in the second loop.

get more rows in JTable java

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);
}
}

JTable not showing output

Here's my code:
private void show(java.awt.event.ActionEvent evt) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "phone";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "school";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement pStmt = conn.prepareStatement("SELECT * FROM contacts");
ResultSet rs = pStmt.executeQuery();
JFrame frame1 = new JFrame();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(300, 150);
frame1.setVisible(true);
while (rs.next() == true) {
Object rowData[][] = {{"Name"},
{"Phone"}};
Object columnNames[] = {"Column One", "Column Two"};
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame1.add(scrollPane, BorderLayout.CENTER);
}
rs.close();
pStmt.close();
conn.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
I want to display the record in a separate window but its showing a blank screen. Any corrections suggested?
Vector columnNames = new Vector();
Vector data = new Vector();
try{
Connection conn = null;
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:XE","yedal ","yedal121288");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("");
ResultSetMetaData meta=rs.getMetaData();
int columns = meta.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( meta.getColumnName(i) );
}
while (rs.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
}
catch (SQLException ex) {
ex.printStackTrace();
}
t= new JTable(data, columnNames); t.setVisible(true);
TableColumn col;
for (int i = 0; i < t.getColumnCount(); i++)
{
col = t.getColumnModel().getColumn(i);
col.setMaxWidth(200);
}
JScrollPane scrollPane = new JScrollPane(t);
You're creating multiple JTables in your while loop, I assume that's not what you're intending to do, and also you don't give them size. you must set the size of JTable with setPreferredSize or setSize method:
tblObj.setPreferredSize(new Dimension(300,400));
also you pass true to setFillsViewportHeight method for your table content to fill the view port.
Here's a link on how to use JTable:
How To Use JTable
I suppose you see an exception java.lang.ArrayIndexOutOfBoundsException if you look into your console. The JTable is populated with a table model which has two columns but you construct it with an array with data of only one.
Please note since you set the frame to visible before this exception occurs, the frame is shown, the component is added to it but when swing tries to paint it it will fail.
If you replace your test data with e.g.
Object rowData[][] = { { "Name", "Phone" }, { "Name2", "Phone2" } };
it'll work (unless rs.next() is never true).
it is better to use a library file rs2xml.jar .
include it into ur library
first create a connection with the database using jdbc.
import this --> import net.proteanit.sql.DbUtils;
String query ="select * from employee"; //let
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
s.append (QueryArea.getText()).append("\n");
jTable.setModel(DbUtils.resultSetToTableModel(rs));
There will be an exception thrown in this ,so handle it by a try catch statement.
if any problem with this u can ask.

Categories