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.
Related
I am trying to get what column and row are selected on a JTable using a clicked Event, but its telling me this - "java.lang.ArrayIndexOutOfBoundsException:-1"
Here is my JTable:
DefaultTableModel tabelaPrs = new DefaultTableModel (null, new String[] {"DATA","EXERCICIO","PESO","NÚMERO DE REPETIÇÕES"});
JTable jtPrs = new JTable(tabelaPrs);
jtPrs.setEnabled(false);
JScrollPane jspPrs= new JScrollPane(jtPrs);
jspPrs.setEnabled(false);
jspPrs.setBounds(55,88,639,567);
jspPrs.setPreferredSize(new Dimension(475,125));
contentPane.add(jspPrs);
My try catch to give the JTable the data from sql:
try
{
java.sql.Statement stmt;
ResultSet rs;
String sql = "SELECT * FROM prs ORDER BY data";
int i = 0;
String [] campos = new String [] {null, null, null,null};
LigacaoBD obterLigacao = new LigacaoBD();
Connection con = (Connection) obterLigacao.OL();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next())
{
tabelaPrs.addRow(campos);
tabelaPrs.setValueAt(rs.getString("data"), i, 0);
tabelaPrs.setValueAt(rs.getString("exercicio"), i, 1);
tabelaPrs.setValueAt(rs.getString("peso"), i, 2);
tabelaPrs.setValueAt(rs.getString("num_reps"), i,3);
i++;
}
obterLigacao.FecharLigacao(con);
}
catch (SQLException sqle)
{
JOptionPane.showMessageDialog(null, "Não foi possivel efetuar a operação na BD." + sqle.getMessage());
}
Here is my Mouse Clicked Event:
jtPrs.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int r = jtPrs.getSelectedRow();
getData = tabelaPrs.getValueAt(r, 1).toString();
getExercicio = tabelaPrs.getValueAt(r, 2).toString();
getPeso = tabelaPrs.getValueAt(r, 3).toString();
getRepetições = tabelaPrs.getValueAt(r, 4).toString();
}
});
Looking at the JavaDocs for JTable, the method JTable.getSelectedRow() returns -1 if no row is selected.
int r = jtPrs.getSelectedRow();
getData = tabelaPrs.getValueAt(r, 1).toString();
You then attempt to use the retrieved value with the JTable, which probably caused the ArrayOutOfBoundsException.
The obvious solution is to make sure a row is selected when that Event is called, so that -1 won't be returned. See this for some details about selecting a row.
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.
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 want to display the data out of my result set into a JTable.
When I run the following code the table doesn't update.
public void getHouses(int price) {
Connection conn;
ArrayList<Integer> ID = new ArrayList<Integer>();
ArrayList<String> Price = new ArrayList<String>();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Houses");
Statement statement = conn.createStatement();
ResultSet rec = statement.executeQuery("SELECT * FROM Houses WHERE Price <= " + price + "");
while (rec.next()) {
ID.add(rec.getInt("ID"));
Price.add(rec.getString("Price"));
}
String[] columnNames = {"House ID", "House Price"};
Object[][] rows = new Object[ID.size()][2];
for (int i = 0; i < ID.size(); i++) {
rows[i][0] = ID.get(i);
rows[i][1] = Price.get(i);
}
jTable1 = new JTable(rows, columnNames);
statement.close();
} catch (SQLException se) {
} catch (ClassNotFoundException cnf) {}
}
NOTE!
I added the JTable to the gui by drag and drop.
I also tested that my resultset has the data in it.
You need to learn about OP Swing MVC pattern, you need to declare a TableModel which your data store then set it to your table, like:
TableModel myData = new DefaultTableModel(columnVector, dataVector);
jTable1.setModel(myData);
Read more about DefaultTableModel
public void search() throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows = new Vector();
for (int i=1; i<columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
for (int j=1; j<columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
tblPatient.setModel(dtm);
}
On my ResultSet rs = state.executeQuery() I used this SQL
"SELECT "
+ "pIDNo AS 'Patient ID',"
+ "pLName AS 'Last Name',"
+ "pFName AS 'First Name',"
+ "pMI AS 'M.I.',"
+ "pSex AS 'Sex',"
+ "pStatus AS 'Status',"
+ "pTelNo AS 'Contact No.',"
+ "pDocID AS 'Doctor ID',"
+ "pAddr AS 'St. No.',"
+ "pStreet AS 'St. Name',"
+ "pBarangay AS 'Barangay',"
+ "pCity AS 'City',"
+ " pProvince AS 'Province',"
+ " pLNameKIN AS 'Last Name',"
+ "pFNameKIN AS 'First Name',"
+ "pMIKIN AS 'M.I.',"
+ "pRelationKIN AS 'Relation',"
+ "pTotalDue AS 'Total Due'"
+ " FROM dbo.Patients");
First I run this line (pTotalDue didn't come up to jTable.)
And on my second attempt to display it I do this:
"SELECT pTotalDue AS 'Total Due' FROM dbo.Patients"
Now I tried this one, and I think something's really wrong about my codes. BTW this column has MONEY DATA TYPE
why does it didn't show to my JTable? could anyone tell me what is the problem with my codes?
(Problem in the answer that has given to me)
public class QueryOnWorkerThread extends SwingWorker{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:OJT_dsn";
String user = "sa";
String pass = "";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
`#Override <<<<<<<<<<<<<<<<<<<<< I have a problem here it says : done() in javaapplication25.SearchPatient.QueryWorkerThread cannot override done() in javax.swing.SwingWorker overriden method does not throw java.lang.Exception , what does it mean sir?`
protected void done() throws Exception{
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
try this
DefaultTableModel dtm=(DefaultTableModel)table.getModel();
for (int i = dtm.getRowCount() - 1; i > -1; i--) {
dtm.removeRow(i);
}
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("Your SQL Query");
while(rs.next())
{
String str1=rs.getString(1);
String str2=rs.getString(2);
String str3=rs.getString(3);
String str4=rs.getString(4);
String str5=rs.getString(5);
:
:
:
dtm.addRow(new Object[]{str1,str2,str3,str4,str5});
}
In you loops, your exit condition is
j<columns
this means thant the last column will never be recovered. try this insted:
for (int j=1; j<=columns; j++)
The fact that your last column does not appear is probably related to your loop statements, as already indicated by #Joan.
There are however more issues with this code. You should only update Swing components on the Event Dispatch Thread, and on that Thread you should not perform long running operations. In short, mixing SQL queries and updates of the JTable should not happen on the same thread. Consult the Concurrency in Swing guide for more info.
Using a SwingWorker could solve this issue:
public class QueryOnWorkerThread extends SwingWorker<TableModel, Void>{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
#Override
protected void done() {
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
}
The SwingWorker can be started by calling
QueryOnWorkerThread worker = new QueryOnWorkerThread( tblPatient );
worker.execute();
Note how I changed the loops in your code
Try getting that column via ResultSet.getBigDecimal() rather than via ResultSet.getString(). Then put your retrieved BigDecimal.toPlainString() into your table cell.
Example:
data_rows.addElement(rs.getBigDecimal("pTotalDue").toPlainString());//Assuming your select returns a pTotalDue Column (e.g. SELECT pTotalDue,... FROM ...)
Try to Use an TableCellRenderer.
Implement the Renderer and render the Column with the Money Type in the form you wish.
Regards,
HL