I'm new in java.
how can I get the data from mysql and display it in Jlist (Jlist name: JLISTF)
I'm confused with vector and the model.
Below is the photo of my JFRAME
the yellow part means JLIST and it's name is JLISTF
I want to display the data from mysql
Thank you
code:
public class Inventory extends javax.swing.JFrame {
Connection connect = null;
ResultSet rs = null;
PreparedStatement pst = null;
ResultSet rs2 = null;
public void populateJList(JList ItemList, String query, Connection connection) throws SQLException
{
DefaultListModel model = new DefaultListModel(); //create a new list model
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query); //run your query
while (resultSet.next()) //go through each row that your query returns
{
String ItemList2 = resultSet.getString("ItemCode"); //get the element in column "item_code"
model.addElement(ItemList2); //add each item to the model
}
ItemList.setModel(model);
resultSet.close();
statement.close();
}
public Inventory() {..}
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) { ......}
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
try{.........}
catch()
{...........}
}
Assuming you have a connection to your database and you know what information you want to query, you can use the following method to populate your JList.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.DefaultListModel;
import javax.swing.JList;
...
public void populateJList(JList list, String query, Connection connection) throws SQLException
{
DefaultListModel model = new DefaultListModel(); //create a new list model
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query); //run your query
while (resultSet.next()) //go through each row that your query returns
{
String itemCode = resultSet.getString("item_code"); //get the element in column "item_code"
model.addElement(itemCode); //add each item to the model
}
list.setModel(model);
resultSet.close();
statement.close();
}
You would pass your JLISTF variable into this function as the first parameter.
The following line assumes that your column name is "item_code", you will want to replace this with your columns actual name.
String itemCode = resultSet.getString("item_code");
This function creates a new Model (see How to Use Models), then executes your query. It gets each value that your query returns and adds it to the new model. list.setModel(model) then tells the list to start using your new model.
Related
I am using a restful web service and I was able to display database records using an array. But I am confused on how will I be able to display my desired record. I have here the class where the SQL query is being executed. I am using Advanced Rest Client google chrome application in testing the response and the output. How will I be able to query 'select * from taxi where taxi_plate_no='inputted data''? I am really confused on how will I be able to do it in an array. Please help me. Thank you! :(
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.ws.rs.QueryParam;
import com.taxisafe.objects.Objects;
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
#QueryParam is annotation used in rest webservices .
And i think here you want to use parameter with your SQL query.
So using parameter in PreparedStatement use following code
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con,String taxiNumber) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi WHERE taxi_plate_no= ?");
stmt.addString(1,taxiNumber);
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
Note: Use parameter taxiNumber or any other parameter you want to
retrive data on that parameter
and use setString(position,value); to replace ? with that parameter
So at the moment I have a class called MySqlConnection with this code inside it
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class MySqlConnection {
public static void Connection() throws Exception {
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Friends", "John", "John123");
// jdbc:mysql://localhost:3306/employee_record --> This is the database
// root is the database user
// root is the password
// Here we create our query
PreparedStatement Statement = con
.prepareStatement("SELECT * FROM names ORDER BY first");
// Creating a variable to execute query
ResultSet result = Statement.executeQuery();
while (result.next()) {
System.out.println(result.getString(1) + " " + result.getString(2));
}
}
}
When I run this, it displays all the results at once in the Eclipse IDE.
http://i.imgur.com/V9kA5fN.png
How do I make it display all the results in a separate window?
You can use JTable on the JFrame to show the data in tabular format on a window. You can find examples on Internet about using JTable.
You can use JTable. Here is my version
public class JResultTable extends JTable {
public DefaultTableModel dataModel;
ResultSet rs;
public void init_model(){
dataModel=new DefaultTableModel();
}
public void add_data() throws SQLException {
String colNames[];
ResultSetMetaData rsMetaData=rs.getMetaData();
int colCount=rsMetaData.getColumnCount();
colNames=new String[colCount];
for(int i=1;i<=colCount;i++)
colNames[i-1]=rsMetaData.getColumnName(i).toUpperCase();
dataModel.setColumnIdentifiers(colNames);
while(rs.next())
{
String[] rowdata= new String[colCount];
for(int i=1;i<=colCount;i++)
rowdata[i-1]=rs.getString(i);
dataModel.addRow(rowdata);
}
}
JResultTable(ResultSet rs) throws SQLException {
super();
init_model();
this.rs=rs;
add_data();
setModel(dataModel);
}
}
Ex- JResultTable mm=new JResultTable(rs)// rs is the resultset. Column Names will automatically become table headers (ResultSetMetaData)
add this mm to a panel or frame.
Below is my code to create a table from my database. I would like to add a checkbox column at the end which will not be in the database. it is just part of the front end. the Could you please help?
my getRow() method keep returning -1 although a row is selected, any suggestion?
package Default;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.sql.*;
/**
* This class create JTable from Database table.
* User program needs to specify database connection and corresponding a table name.
*
*/
public class DBTable{
//private String table;
DefaultTableModel dm=new DefaultTableModel();
JTable t1=new JTable();
Object row[];
String c[];
int cols;
PreparedStatement pst;
ResultSet rs ;
public DBTable(Connection conn){
conn=Login.con;
}
/**
* This method return JTable object created from Database table having selected data and structur * as in original table into database.
* #param table Name of the database table to be coverted to JTable
* #param query Select query to specify selected columns and data to extracted from database table
* #return JTable object that consist of selected data and structure of Database table
* #throws java.lang.Exception Original object is deferent, e.i either SQLException or NullPointerException
*/
public JTable getTable(String table,String query)throws Exception{
JTable t1=new JTable();
DefaultTableModel dm=new DefaultTableModel();
Statement st= Login.con.createStatement();
ResultSet rs=st.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
//Coding to get columns-
int cols=rsmd.getColumnCount();
String c[]=new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
dm.addColumn(c[i]);
}
//get data from rows
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
t1.setModel(dm);
return t1;
}
public int getRow(){
int row = t1.getSelectedRow();
JOptionPane.showMessageDialog(null, row);
return row;
}
public void deleteRow(String sql){
try {
String value = (String) t1.getValueAt(getRow(), 0);
JOptionPane.showMessageDialog(null, value);
pst = Login.con.prepareStatement(sql);
pst.setString(1, value);
((DefaultTableModel)t1.getModel()).removeRow(getRow());
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
}
You are using a DefaultTableModel so after you create the model you can manually add a column:
model.addColumn("CheckBox Column");
I have a JDBC:ODBC connection to a MS Access Database which populates a JTable with DButils. My basic SQL queries work fine until I try the COUNT function and then I get errors when trying to populate my JTable. The query works fine to populate a JTextArea so I know the query is ok.
My code is below any help would be greatly appreciated.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class table {
Connection con;
Statement st;
ResultSet rs;
public table(){
connect();
}
public void connect(){
JTable tbl = new JTable();
tbl.setDefaultEditor(Object.class, null);
JFrame resFrame = new JFrame("Results");
resFrame.setLayout(null);
resFrame.setSize(525, 445);
resFrame.setVisible(true);
JScrollPane tsp = new JScrollPane(tbl);
tsp.setLocation(20, 20);
resFrame.add(tsp);
tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tsp.setSize(370,375);
String sql = "SELECT Club, COUNT('memberID') AS total FROM Members_Table, Club_Table WHERE Club_Table.clubID=Members_Table.clubID GROUP BY Club";
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:ITUKdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery(sql);
tbl.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
}
}
}
The error I get is below
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3906)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5697)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:353)
at sun.jdbc.odbc.JdbcOdbcResultSet.getObject(JdbcOdbcResultSet.java:1677)
at net.proteanit.sql.DbUtils.resultSetToTableModel(DbUtils.java:28)
at trial.table.connect(table.java:53)
at trial.table.<init>(table.java:22)
at trial.ITUKSQL.main(ITUKSQL.java:212)
Sorted had to remove
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE
From
st = con.createStatement();
import java.sql.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
import java.util.Vector;
public class SimpleTable extends JFrame {
public SimpleTable() {
super("Simple JTable Test");
setSize(350, 200);
//setLocation(250,300);
int ColCount;
int i;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/employ_details","root","");
java.sql.Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery("select * from employe_details ");
ResultSetMetaData meta =rs.getMetaData();
ColCount=meta.getColumnCount();
String s1 = null;
String s2 = null;
String s3 = null;
String s4 = null;
String s5 = null;
String s6 = null;
String s7 = null;
while (rs.next())
{
String [] record= new
String[ColCount];
for (i=0; i<ColCount; i++)
{
record[i]=rs.getString(i+1);
s1= rs.getString("Employee_ID");
s2= rs.getString("Employee_Name");
s3= rs.getString("Contact_Number");
s4 = rs.getString("Address");
s5 = rs.getString("Email");
s6 = rs.getString("dob");
s7 = rs.getString("Sex");
}
JTable jt = new JTable(new String[][]{{s1,s2,s3,s4,s5,s6,s7}}, new String[]{"Employee_ID","Employee_Name","Contact_Number","Address","Email","dob","Sex"});
JScrollPane jsp = new JScrollPane(jt);
getContentPane().add(jsp,BorderLayout.CENTER);
}}
catch (Exception e)
{
System.out.println("failure to connect " + e);
return; //(exit(1));
}
}
public static void main(String args[]) {
SimpleTable st = new SimpleTable();
st.setVisible(true);
}
}
its only shopwing the last row in the database .
how i get all the rows in the database to the JTable ?
Your code is reading all the data but it doesn't store all, it holds data of last loop execution only.
And creating table from last row so it will show last row only.
Try something like
List<String> data = new ArrayList<String>();
than
while (rs.next())
{
String [] record= new
String[ColCount];
for (i=0; i<ColCount; i++)
{
record[i]=rs.getString(i+1);
data.add(rs.getString("Employee_ID"));
data.add(rs.getString("Employee_Name"));
.
.
.
data.add(rs.getString("Sex"));
}
JTable jt = new JTable(new String[][]{data.toArray()}, new String[]{"Employee_ID","Employee_Name","Contact_Number","Address","Email","dob","Sex"});
You are iterating through the ResultSet and no storing all the values of returned by the ResultSet.
Your s1..s7, therefore, holds the last value from the resultset. You can either have s1[]..s7[] to hold all values, per column, from the resultset or have a List of all values in the set.
Best way, is to create a POJO object to map your entity (POJO) to your SQL table.
This is an easier problem if you break it into smaller steps.
Instead of putting all your code into one main method, I'd recommend breaking them into several smaller classes. Focus on one, get it working, then move onto the next thing.
Your first problem is data retrieval.
Java's an object-oriented language: start with an Employee class.
package model;
public class Employee
{
private String id;
private String name;
private String phone;
private String address;
private String email;
private Date birthday;
private Gender gender;
// Constructors, getters/setters, equals, hashCode, toString and behavior follow.
}
Once you have that written and tested, write a data access object to deal with the database:
package persistence;
public interface EmployeeDao
{
List<Employee> find();
Employee find(String id);
List<Employee findByName(String name);
void save(Employee e);
void update(Employee e);
void delete(Employee e);
}
Write an implementation for this and get it tested.
Only worry about the JTable when you've got these working. Your problems will be isolated to the UI at that point, because you've got the persistence sorted out.