String sql = "SELECT ID, NAME, SALARY FROM EMPLOYEE";
public List<Employee> getAllEmployees(Connection con){
List<Employee> elist = new ArrayList();
try{
//prepared statement
//
//
}catch(){
//exception
}
return elist;
}
Guys, I have a java class which selects List of values from DB. So far my code is running good I did debugging and I can see my query in eclipse console. Now I need to display java returned value(LIST) with different data types in jsp page. I am stuckI somehow I need to loop javaclass return value or something and display in jsp page. Please help me I have spent 2 hrs and can't come up with anything. i am uisng struts 2.0 and Employee class contains setter/getter
String sql = "select ID, NAME, SALARY FROM EMPLOYEE";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
you have to store all the data into ResultSet. Than you have to create Arraylist.
List<Integer> values = new ArrayList<>();
values.add(index,rs.next());
values.add(index1,rs.next());
//This is way to your code. not complete code of yours.
Related
I am creating a Simple Payroll System for my Final Year Project.i ran in to problem with add the leave to employee. if i add the leave it will added to all the employee belong to the company.but i couldn't do the task what i tried so i written below of code.
For the example
if i selected the leave casual leave as 20 days . it added all employee no in the list.
Employee Table
Leave Table
Code which i tried so
String cas = txtcas.getValue().toString();
String anu = txtanu.getValue().toString();
String med = txtmed.getValue().toString();
String year = txtyear.getText();
try {
int c;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/spay","root","");
PreparedStatement pst1 = con.prepareStatement("select empno from employee");
ResultSet rs = pst1.executeQuery();
ArrayList<String> empnos = new ArrayList<>();
while (rs.next()) {
empnos.add(rs.getString(1));
pst = con.prepareStatement("insert into leaves(empno,casual,annual,address,medical,year)values(?,?,?,?,?)");
pst.setString(1,) ); // employee no how to give here
pst.setString(2, cas);
pst.setString(3, anu);
pst.setString(4, med);
pst.setString(5, year);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Leave Insertedddddd");
}
Database output comes to look like this
// This is the code to get the data from table for a particular column.
String empNoValue;
while (rs.next()) {
empNoValue = rs.getString("empno"); // empno is the column name
}
Before that,
1 you need to add the some WHERE Condition for taking the specific employee in query pst1.
Otherwise,
1 You need to set the session value or the hidden value from the before page for that employee.
1.1 After that you got the specific employee (from that hidden or session value) whose data add to the table.
String employeeValue = hidden or session value // from privious page
then add the employeeValue to the insert query like below
pst.setString(1, employeeValue); // employeeValue is the your specific empno get from privious page
I am assuming that pst1 is declared somewhere earlier in the code, and in
ResultSet rs = pst.executeQuery();
you are actually calling pst1 and not pst
For the required output you need to iterate over the result set, something like this
PreparedStatement pst1 = con.prepareStatement("select empno from employee");
ResultSet rs = pst1.executeQuery();
List<String> empnos = new ArrayList<>();
while (rs.next()) {
empnos.add(rs.getString(1));
}
and then use the arraylist for your usecase
Do read about getting the result set values on internet as well, it will help you for your future questions
Well, I needed to take values from the database, and insert them into the combobox for selection.
Sounds easy enough to do just using 2 classes, UI class and Entity class, which contains all the SQL queries inside (anything to do with database, it's in there):
//This is the UI class
public void fillComboBox(){
Entity et = new Entity();
try{
//call out dbConnector method from Entity class
conn = et.dbConnector();
String query="select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows topic data in combobox
comboBoxName.addItem(rs.getString("Name"));
}
}
catch(Exception e){
e.printStackTrace();
}
}
//runs method
fillComboBox();
Now, the above output works fine with no hitches. In my form, the combo box displays unique values taken from my database in my specified column.
The problem comes when implementing another tier within it.
In short, I have three classes now.
Class 1: UI -> this class purely handles UI
Class 2: Controller -> this class purely runs methods
Class 3: Entity -> this class purely runs anything that have to do with sql database queries
What I did, was to modify the above code, into this:
This is the UI class:
//Declare Variables
JComboBox comboBoxName = new JComboBox();
Controller ct = new Controller();
comboBoxName.addItem(ct.fillComboBox());
And a certain method within the Controller class:
//Declare Variables
Entity et = new Entity();
public String fillComboBox(){
return et.takeNames();
}
Lastly, my Entity class, which contains all sql queries within.
//Declare all variables first
Connection conn = null;
String task = null, names = null;
String query;
//This method connects to database
//There's nothing wrong with this method, I just placed it here to give a general overview of what this method exactly is for you to understand, as I will be calling it out later. Yes, I removed off the **URL** portion intentionally.
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:URL");
JOptionPane.showMessageDialog(null, "Connected!");
return conn;
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
return null;
}
}
public String takeNames(){
try{
conn = dbConnector();
query = "select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows Name data in combobox
names = rs.getString("Name");
}
pst.close();
}
catch(Exception ex){
ex.printStackTrace();
}
return names;
}
Well, basically, how this "new" implementation runs is that, the UI class calls out the Controller class, which calls out the Entity class, which runs the method inside and parse back values all the way to UI.
This method is useful in the sense that it separates different portions of a program, making it look neater. Too bad it is a headache to implement. >.>
Now, the error in this would be that, it will retrieve only 1 value, instead of multiple values. What it does retrieve is the very first 'distinct' value in that particular column I specified. The remaining 'distinct' values are ignored.
I have a hunch it had everything to do with the rs setting, #:
ResultSet rs = pst.executeQuery();
What I had in mind was that it only takes 1 value and sets it, then ignores the rest. Does anyone have any solutions for this? I tried arraylist but failed on how to store numerous rs values in the arraylist (this really stumped me >.>)
I do apologize for the lengthy post, but I tried my best to do up till what I can, before I got stuck at this part for hours.....
modify takeNames() as follows
public ArrayList<String> takeNames(){
//This will collect all names from db
ArrayList<String> names = new ArrayList<>();
try{
conn = dbConnector();
query = "select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows Name data in combobox
//Add data to the array list
names.add(rs.getString("Name"));
}
pst.close();
}
catch(Exception ex){
ex.printStackTrace();
}
//Return the array list you created
return names;
}
Modify fillComboBox() as follows
public ArrayList<String> fillComboBox(){
return et.takeNames();
}
And modify the rest as follows
JComboBox comboBoxName = new JComboBox();
Controller ct = new Controller();
ArrayList<String> nameList = ct.fillComboBox();
for(String name : nameList){
comboBoxName.addItem(name);
}
How do you go about putting records into a jTextField when an item is selected from a jComboBox? For example, I'm making an airline reservation system and I have a combo box with the available flights. Below it are text fields with designated info like departure date, departure time, arrival date, etc. How do I make it so that when the user selects an item from the the combo box, (ex. flight name is CX9005) the corresponding info from the same row is shown in the text fields? (ex. departure date is November 12 2015)
EDIT:
So I tried doing that with the ff. code, but I got a syntax error and a ResultSet not open error.
private void combo_FlightItemStateChanged(java.awt.event.ItemEvent evt) {
try{
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
rs = stmt.executeQuery(query);
}
catch(SQLException err){
JOptionPane.showMessageDialog(UserModule.this, err.getMessage());
}
}
Also, I use this function to connect to my database if that matters.
public void DoConnect() {
try{
String host = "jdbc:derby://localhost:1527/UserAccounts";
String uName = "Bryan";
String uPass = "Cruz";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ACCOUNTS";
rs = stmt.executeQuery(sql);
}catch(SQLException err){
JOptionPane.showMessageDialog(Connect.this, err.getMessage());
}
}
Also, I might not have been too clear with my original post. I want to make it so that when the user selects a flight from the combo box, all of that flight's details show up in the appropriate text fields. (ex. departure date, departure time, destination, etc.) I'm confused on how to make this work so help would be much appreciated!
You get the text from the comboBox using getSelectedItem() or getSelectedValue().
You can then create a MySQL query like:
String flightName = yourComboBox.getSelectedItem().toString();
String query= "Select * from yourTable where flightName = \'"+flightName+"\';";
Then you can execute this query using executeQuery()
Now for the part with setting results in all testfields
First store the result in a ResultSet object
rs = stmt.executeQuery(query);
rs.next();
Now you have the result in object rs
Use rs.getString(columnNumber) to get records from the result
Eg.
String departureDate = rs.getString(4);
// assuming the column number is 4
Do this to get all required strings.
And set them in respected columns using setText() method
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
What is the point of the above two statements? You can't get two values from the same combo box. Either you get the flightID or the flighName.
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
but I got a syntax error
Don't try to build the SQL string manually. Instead you can use a PreparedStatement. It will make sure the proper delimiters are used so you just concentrate on the SQL statement:
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString( 1, flightName );
ResultSet rs = stmt.executeQuery();
So you will need access to the Connection object you established in the doConnect() method. Note, method names should NOT start with an upper case character.
Also, I believe the standard for database column names is to capitalize the words of the column, so you should be using "FlightName" not "flightName" as the column name.
So say a column is named Names I want to get a ArrayList of every variable inside of this column. Example:
Names
Test
Test1
Test3
River
World
Etc
I want to get all of that into an array list. Thanks for the help!
You're not giving much information in your question (e.g. what is the table you'd like to query), so here's a somewhat generic solution:
public List<String> retrieveAllColumnValues(Connection connection) throws SQLException {
String query = "SELECT Names FROM MyTable";
List<String> values = new ArrayList<>();
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
values.add(rs.getString("Names"));
}
rs.close();
}
return values;
}
Getting data from the database through JDBC roughly consist of the following parts:
You have a Connection which you use for creating SQL Statements
When you execute the Statement, you get a ResultSet, which contains the values returned by your query
You iterate through the ResultSet and do what you need to with the values
If I'm not mistaken, a preparedStatement is destroyed from cache once a connection is closed. At the moment my app is setup so that I have a function to get POJO objects from the database based on the single POJO object passed in. I then have another function to get id's of ALL objects in that table for cases where I need a list, and then in the while loop of that function I get the entire objects one at a time.
However doing this doesn't take advantage of cached queries right? So what is the best way to have a generic getter SQL function that can make use of cached preparedstatements if it is a list of items or a single item? In PHP I can do this easily by checking if the passed in param is an array or not, but Java requires you to define the param object.
So for example, let's say users, here is what I currently have:
//Get user object
public User getUser(User user) throws SQLException {
Connection connection = connectionWrapper.getConnection();
String query = "SELECT firstName, lastName FROM users WHERE userId = ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setInt(1, user.getUserId());
ResultSet rs = statement.executeQuery();
if (rs.next()) {
//Get database details and set into object
}
rs.close();
statement.close();
connection.close();
}
//Get all users
public List<User> getAllUsers() throws SQLException {
List<User> userArr = new ArrayList<User>();
Connection connection = connectionWrapper.getConnection();
String query = "SELECT userId FROM users";
PreparedStatement statement = connection.prepareStatement(query);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
int id = rs.getInt("userId");
User user = new User(id);
getUser(user);
userArr.add(user);
}
rs.close();
statement.close();
connection.close();
return userArr;
}
It would be nice to be able for the getUser function to handle both an individual object case like above and an array case where an array of user objects (with userId's set) are passed in and it loops through the array to get all objects before closing the connection. Is there a non-messy way to do this or should I just pass a User array to the getUser function in all cases, even if it's just one?
If what you're after is performance, then executing 5 queries to find 5 users given an array of 5 IDs is not really the best solution. You'd better execute a single query that loads all the users at once, using
select firstName, lastName FROM users WHERE userId in (?, ?, ?, ?, ?)
Similarly, your getAllUsers() method is extremely inefficient. It should execute a single query, instead of executing a query to get all the IDs, and then a query for every ID found.