java- mysql data retriving problem - java

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.

Related

Java: How to return JDBC queries from JcomboBox

package userProfile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Database extends JFrame implements ActionListener {
JFrame frame;
JButton search, mainMenu;
JComboBox fromLoc, toLoc, fromDate, fromTime;
JLabel fromLabel, toLabel, fromDateLabel, fromTimeLabel;
PreparedStatement ps = null;
Connection link;
ResultSet rs = null;
public Database() {
frame = new JFrame("Make a Reservation");
frame.getContentPane().setLayout(null);
//Arrival date/time comboBoxes and labels
fromDateLabel = new JLabel("Departure Date");
fromDateLabel.setBounds(50,230,100,30);
fromDate = new JComboBox(new String[]{"12/15/2015",
"12/21/2015", "12/21/2015", "12/24/2015"});
fromDate.addActionListener(this);
fromDate.setBounds(50,200,100,30);
/*
fromTimeLabel = new JLabel("Departure Time");
fromTimeLabel.setBounds(160,230,100,30);
fromTime = new JComboBox(new String[]{"13:00","15:00", "15:30", "08:00"});
fromTime.addActionListener(this);
fromTime.setBounds(160,200,100,30);
*/
//Departure label and comboBox
fromLabel = new JLabel("Departure");
fromLabel.setBounds(50,300,100,30);
fromLoc = new JComboBox(new String[]{"Atlanta", "Charleston", "New York", "Los Angeles", "Orlando", "San Francisco"});
fromLoc.addActionListener(this);
fromLoc.setBounds(50,270,100,30);
toLabel = new JLabel("Arrival");
toLabel.setBounds(160,300,100,30);
toLoc = new JComboBox(new String[]{"Atlanta", "Charleston", "New York", "Los Angeles", "Orlando", "San Francisco"});
toLoc.addActionListener(this);
toLoc.setBounds(160,270,100,30);
search = new JButton("Ok");
search.addActionListener(this);
search.setBounds(270,270,100,30);
//adding the buttons in frame
frame.getContentPane().add(fromDateLabel);
frame.getContentPane().add(fromDate);
frame.getContentPane().add(fromTimeLabel);
frame.getContentPane().add(fromTime);
frame.getContentPane().add(fromLabel);
frame.getContentPane().add(fromLoc);
frame.getContentPane().add(toLabel);
frame.getContentPane().add(toLoc);
frame.getContentPane().add(search);
frame.setSize(400,400);
frame.setVisible(true);
try {
// Driver for mysql
Class.forName("com.mysql.jdbc.Driver");
// connection link obj
link = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root", "root");
// query statement obj
} catch (SQLException sqle) {
System.out.println("An error occurred.Maybe user/password is invalid");
sqle.printStackTrace();
} catch (ClassNotFoundException cfne) {
cfne.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e) {
JComboBox fromLoc = (JComboBox)e.getSource();
String fromL = fromLoc.getSelectedItem().toString();
JComboBox fromDate = (JComboBox)e.getSource();
String fromD = fromDate.getSelectedItem().toString();
JComboBox toLoc = (JComboBox)e.getSource();
String toL = toLoc.getSelectedItem().toString();
ArrayList<Flights> results = new ArrayList<>();
try {
ps = link.prepareStatement("select * from flights where from_date = ? and from_loc = ? and to_loc = ?");
ps.setString(1, fromD);
ps.setString(2, fromL);
ps.setString(3, toL);
rs = ps.executeQuery();
while(rs.next()) {
Flights flight = new Flights();
flight.setFromD(rs.getString("from_date"));
flight.setFromL(rs.getString("from_loc"));
flight.setToL(rs.getString("to_loc"));
results.add(flight);
}
} catch (SQLException sqle) {
System.out.println("An error occurred.Maybe user/password is invalid");
sqle.printStackTrace();
}
}
}
I'm getting an NullPointerException when running this. This program should query database using hard-coded strings from an array in 3 comboBoxes and save returned strings as objects into an ArrayList.
Please help, again
Thanks
I would create a Flight model class and use it as a DTO. So, in your while(rs.next) i would use the the result to instantiate Flight objects and add them to an ArrayList<Flight> which could be returned to where ever you need to use it.
Your 3rd question I'm not quite sure about since i havn't worked a lot with Swing.
Hope my response is helpful to you. If I misunderstood your question please let me know.
EDIT:
A DTO is a Data Transfer Object used for contain and transfer data. So a Flight class could look like this:
public class Flight{
public String fromD;
public String fromL;
public String toL;...
//And so on
//You also need setters and getters
}
Then in your Database class:
ArrayList<Flight> results = new ArrayList<>();
while(rs.next){
Flight flight = new Flight();
flight.setFromD(rs.getString("columnname"));
//Same method for the other variables you need to set.
results.add(flight);
}

Jtable how to display data from mysql in different Columns

I am trying to display data from the database in java using Jtable, yes I have achieved that but now the conflict is the surname and name they are displayed in one Column yet I would like them to be displayed in different columns . below is my code please help ..
import java.awt.Dimension;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ju {
private static Object request;
static JTable mysTable;
//constructor method
public static void main (String args []){
String [] columnNames = {"Name","Lastname","Id","Style"};
mysTable = new JTable(4,4);
mysTable.setBounds(20,10,300,300);
JFrame frame = new JFrame("King Musa Saloon Software");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(500,500);
frame.setResizable(false);
frame.setVisible(true);
frame.add(mysTable);
//frame.add(mysTable);
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loading success!");
String url = "jdbc:mysql://localhost:3306/saloon";
String name = "root";
String password = "";
try {
java.sql.Connection con = DriverManager.getConnection(url, name, password);
System.out.println("Connected.");
// pull data from the database
java.sql.Statement stmts = null;
String query = "select userid, username, name from saloonuser ";
stmts = con.createStatement();
ResultSet rs = stmts.executeQuery(query);
int li_row = 0;
while(rs.next()){
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
int userid = rs.getInt("userid");
String username = rs.getString("username");
String name1 = rs.getString("name");
System.out.println(name1);
li_row++;
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Take a look at your code here:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
It's writing in the same column, you should change it to:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,1);
Try and see if it work :)

Java program to pass List of Bean to a oracle stored procedure - Pass entire list at one shot rather than appending objects one after the other

I have the following set of TYPE, PROCEDURE and Java code. I am able to call the stored procedure successfully but i have to append the objects one after the other. I want the process to be happening at one shot as i am dealing with over 50K+ records. Can anyone please let me know what changes needs to be done so that i can send the entire list at one. The code can be found below.
TYPES:
CREATE OR REPLACE TYPE CER_GL_ENTRY_TYPE AS OBJECT
(idKey NUMBER(10) );
CREATE or REPLACE TYPE CER_GL_ENTRY_TYPE_LIST AS TABLE OF CER_GL_ENTRY_TYPE;
PROCEDURE:
CREATE OR REPLACE PROCEDURE GL_PROCESS_BULK_ENTRIES (
p_array IN CER_GL_ENTRY_TYPE_LIST ,p_status OUT VARCHAR2)
AS
v_count NUMBER(5);
row_detail CER_GL_ENTRY_TYPE;
BEGIN
--p_arr_int := NEW array_int ();
--p_arr_int.EXTEND (10);
--len := p_array.COUNT;
v_count := 0;
FOR i IN 1 .. p_array.COUNT
LOOP
row_detail := p_array (i);
DBMS_OUTPUT.put_line('hello');
DBMS_OUTPUT.put_line (row_detail.idKey);
--p_arr_int (i) := v_count;
v_count := v_count + 1;
p_status := 'true';
END LOOP;
DBMS_OUTPUT.put_line (v_count);
DBMS_OUTPUT.put_line (p_status);
EXCEPTION
WHEN OTHERS
THEN
-- handle errors here...
DBMS_OUTPUT.put_line ('Error: ' || SUBSTR (1, 255, SQLERRM));
END;
/
Java Bean:
import java.sql.SQLData;
import java.sql.SQLException;
import java.sql.SQLInput;
import java.sql.SQLOutput;
public class SampleListenerBean implements SQLData
{
private String sql_type="CER_GL_ENTRY_TYPE";
private int id;
public SampleListenerBean() {
}
public SampleListenerBean(String sqlType, int id) {
this.sql_type = sqlType;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSQLTypeName() throws SQLException {
return sql_type;
}
public void readSQL(SQLInput stream, String typeName) throws SQLException {
sql_type = typeName;
id = stream.readInt();
}
public void writeSQL(SQLOutput stream) throws SQLException {
stream.writeInt(id);
}
}
Main class:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
public class StProcExample {
public static void main(String args[]){
Connection con=null;
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());
con = DriverManager.getConnection("jdbc:oracle:thin:#******:1521: TUW1", "*******", "*********");
String query = "{call GL_PROCESS_BULK_ENTRIES(?,?)}";
CallableStatement cs = con.prepareCall(query);
ArrayDescriptor des = ArrayDescriptor.createDescriptor("CER_GL_ENTRY_TYPE_LIST", con);
List<SampleListenerBean> sampleLst = new ArrayList<SampleListenerBean>();
SampleListenerBean bean = null;
for (int i = 0; i < 20; i++) {
bean = new SampleListenerBean("CER_GL_ENTRY_TYPE",i);
sampleLst.add(bean);
}
SampleListenerBean emp=new SampleListenerBean("TS.TEST_EMP_OBJ",234);
SampleListenerBean emp1=new SampleListenerBean("TS.TEST_EMP_OBJ",235);
Object[] employees= new Object[]{emp,emp1};
Object[] employees= new Object[]{sampleLst};
ARRAY a = new ARRAY(des, con, employees);
cs.setObject(1, (Object)a);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
String status = cs.getString(2);
System.out.print("The status is " + status);
if (cs != null) {
cs.close();
}
}
catch(SQLException e){
e.printStackTrace();
}
}
}
I want is the replacement for the following piece of code
SampleListenerBean emp=new SampleListenerBean("TS.TEST_EMP_OBJ",234);
SampleListenerBean emp1=new SampleListenerBean("TS.TEST_EMP_OBJ",235);
Object[] employees= new Object[]{emp,emp1};
ARRAY a = new ARRAY(des, con, employees);
cs.setObject(1, (Object)a);
Instead of setting each object separately, i want to directly use sampleLst instead of the Object array "employees". When i deal with 50K+ objects i cannot keep adding them to the object[]. i will run into heap problems as well. Can anyone please help me out here?
I would use a simpler table type:
CREATE OR REPLACE TYPE NUM_ARRAY AS TABLE OF NUMBER;
And then somewhat simplify the stored procedure:
CREATE OR REPLACE PROCEDURE GL_PROCESS_BULK_ENTRIES (
p_array IN NUM_ARRAY,
p_status OUT VARCHAR2)
IS
...
You then create an array of Integer that will easily fit in memory:
Integer[] idArray = new Integer[50000];
// fill the array of integers here
for (int i = 0; i < idArray.length; i++)
idArray[i] = ....;
ARRAY a = new ARRAY(des, con, idArray);
cs.setObject(1, (Object)a);
There's no need to create any heavy-weight beans just to pass a list of IDs.

how to get data from mysql to jList?

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.

Make linked directories

I have a class that pulls in an id, name and (if needed) parent-id, it converts these into objects and then links them.
If you look right at the end you will see what Im trying to fix at the moment, The folder objects know if they have a child and/or parent but if I were to run mkDirs() here it would only work for two levels (root, child-folder) but if there were multipul levels (root/folder1/folder1) it would not work.
Any Idea how I can solve this?
package stable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class Loop {
public static void main(String[] args) {
int PID = 0;
int RepoID = 1;
Connection con = null;
String url = "jdbc:mysql://localhost/document_manager";
String user = "root";
String password = "Pa55w0rd";
try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
Map<Integer,Folder> data = new HashMap<Integer,Folder>();
while( PID < 50 )
{
try {
Statement st = con.createStatement();
ResultSet result = st.executeQuery("SELECT name, category_id, parent_id FROM categories WHERE parent_id = '"+PID+"' AND repository_id = '"+RepoID+"'");
while (result.next ())
{
String FolderName = result.getString ("name");
String FolderId = result.getString ("category_id");
String ParentId = result.getString ("parent_id");
int intFolderId = Integer.parseInt(FolderId);
int intParentId = Integer.parseInt(ParentId);
System.out.println( FolderId+" "+FolderName+" "+ParentId );
Folder newFolder = new Folder(FolderName, intFolderId, intParentId);
data.put(newFolder.getId(), newFolder);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
PID++;
}
for(Folder folder : data.values()) {
int parentId = folder.getParentFolderId();
Folder parentFolder = data.get(parentId);
if(parentFolder != null)
parentFolder.addChildFolder(folder);
//Added
System.out.print("\n"+folder.getName());
if(parentFolder != null)
System.out.print(" IS INSIDE "+parentFolder.getName());
else
System.out.print(" HAS NO PARENT!");
}
}
}
Looks like you could/should break out the directory creation logic into its own function and then make it recursive. That should get you the ability to make 'infinite' depth directory hierarchies.
Side note: Its horribly inefficient to make repeated DB calls in a loop. Try a single Select and then loop thru results. If needbe, you can use SQL's 'IN' operator to filter results:
http://www.w3schools.com/sql/sql_in.asp

Categories