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.
Related
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.
Hey I don't know how to a the value from jTablePM ( but just first values in the first column) . After that I would like to insert them to the database. All I want to do is to just get songID from jTablePM and write it to database.
Can someone help me ?
Sorry for the messiness..
private void jButton38MouseReleased(java.awt.event.MouseEvent evt) {
String playlistname;
int playlistNum = 0;
try{
pst = conn.createStatement();
rs = pst.executeQuery("select max(playlist_id) from playlist;");
while (rs.next()) {
playlistNum = rs.getInt(1);
}
playlistNum += 1;
String userID = jLabel1.getText();
pst = conn.createStatement();
playlistname = jTextField2.getText();
String addPlaylist = "INSERT INTO playlist (playlist_id, userID, playlist_name, songID)" + "VALUES('"+ playlistNum + "', '" + userID + "','" + playlistname + "', 'songID');" ;
pst.executeUpdate(addPlaylist);
conn.close();
//rs.close();
//pst.close();
}
catch(Exception e){
System.out.println(e);
}
And the code with jTable data:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
PlaylistMaker frame3 = new PlaylistMaker(); // Frames changing
AddToPlaylist.this.setVisible(false);
frame3.setVisible(true);
TableModel model1 = jTable1.getModel();
int[] index = jTable1.getSelectedRows();
Object[] row = new Object[5];
DefaultTableModel model2 = (DefaultTableModel) frame3.jTablePM.getModel();
for(int i = 0; i < index.length; i++) {
row[0] = model1.getValueAt(index[i], 0);
row[1] = model1.getValueAt(index[i], 1);
row[2] = model1.getValueAt(index[i], 2);
row[3] = model1.getValueAt(index[i], 3);
row[4] = model1.getValueAt(index[i], 4);
model2.addRow(row);
}
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.
I am new to Java and I am practicing some new stuff.. I've started working with the database. therefore I made a to do list application with the MVC pattern.
In my Model I get all the results. In My view I try to output this data as a nice table. The problem is that I don't get any output except for a hardcoded piece of code..
here is the code of my view
JTable table = null;
public ToDoListView(ToDoListModel model) {
this.model = model;
setBackground(Color.WHITE);
JTable table = new JTable();
DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{},new String[]{"To do","Date added"});
table.setModel(tableModel);
// this one below is outputted
tableModel.addRow(new Object[]{"something","1-1-2012"});
// this should give me all the results..
for(int i = 0; i < model.getRows().size(); i++) {
tableModel.addRow(model.getRows());
System.out.println("added");
}
add(table);
}
in my Model I have this
private Vector<String> rijen = new Vector<String>();
public void getValue() {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = db.connectToAndQueryDatabase("test", "root", "root");
System.out.println("connection established");
st = con.createStatement();
String query = "SELECT id, item, datum FROM toDoList";
rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getInt("id") + "\n" + rs.getString("item") + "\n" + rs.getDate("datum"));
rijen.add(rs.getInt("id") + "");
rijen.add(rs.getString("item"));
rijen.add(rs.getDate("datum") + "");
}
public Vector<String> getRows() {
return rijen;
}
This is all the relevant code.. I don't know what I miss or what I do wrong. Could someone show me how I could solve it :)?
// This JTable attribut ...
JTable table = null;
public ToDoListView (ToDoListModel model) {
this.model = model;
setBackground (Color.WHITE);
// is hidden by this local variable:
JTable table = new JTable();
In your ToDoModel class you add all data in one large Vector
while(rs.next()) {
System.out.println(rs.getInt("id") + "\n" + rs.getString("item") + "\n" + rs.getDate("datum"));
rijen.add(rs.getInt("id") + "");
rijen.add(rs.getString("item"));
rijen.add(rs.getDate("datum") + "");
}
Then you loop over that Vector to add all those items to the TableModel, but that loop is incorrect
for(int i = 0; i < model.getRows().size(); i++) {
tableModel.addRow(model.getRows());
System.out.println("added");
}
You always add the whole vector instead of just the data for that row.
Combine that with the answer of #user unknown and you might be able to fix your problem
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.