I want to get the DAO list values in controller.like my list contain 10 values i want all the 10 values in controller in 10 separate object or variable.`public List getcountrydata() throws Exception {
conn = connectionDB.getConnection();
Statement stmt = conn.createStatement();
List<wrapper> list = new ArrayList<wrapper>();
list.clear();
ResultSet rs1 = stmt.executeQuery("select * from country ORDER BY country_code ASC");
while (rs1.next()) {
wrapper obj1 = new wrapper();
obj1.setCountry_name(rs1.getString("country_name"));
obj1.setCountry_id(rs1.getInt("country_id"));
list.add(obj1);
}
return list;
}`
From the above code I want to get the country_name and country_id in controller in separate variable like,
String country_name=country_name;
int country_id=country_id;
Use Environment.NewLine where you want to need new line after EOL.
Hope that will help you.
If you are trying to show/save the text of the TextBox you need to create a JavaScript function which runs on submit button push, The process of this function is to change every enter key pressed into <br/> this would show as well as save requirement Format.
Related
when i click button , it show one value . Then i click again and it's still the same ,how to click button and it show a new value next ?
try {
String bdUrl = jdbc:sqlserver://127.0.0.1:1433;databaseName=login;user=sa;password=123;"
Connection conn = DriverManager.getConnection(bdUrl);
String sql = "select cauhoi , caul,cau2,cau3,caudung from tracnghiem";
Statement statement = conn.createStatement();
Resultset rs = statement.excuteQuery(sql);
while (rs.next())
{
String cauhoil = rs.getString(1);
String dapana = rs.getString(2);
String dapanb = rs.getString(3);
String dapanc = rs.getString(4);
String dapand = rs.getString(5);
lbl.setText(""+cauhoil);
jrd1.setText(dapana);
jrd2.setText(dapanb);
jrd3.setText(dapanc);
jrd4.setText(dapand);
}}
catch (Exception e)
{
System.out.println(e);
}
It shows the same value because your SQL statement is the same every time it is executed. You will always see the last value in the ResultSet since you keep updating the Swing components inside the loop.
Instead you need to:
create a custom object to store each of the 5 values for each row of data in the database
Then you need to read the data once and inside your while loop you need to create an instance of this object with each of the 5 values.
This object will then be added to an ArrayList
When you click a button you get an object from the ArrayList and display the values in your Swing components.
You then increment an index variable so that then next time you click a button you get the next object from the ArrayList.
Kindly help me to solve this problem, also tell me how to display data on the table by using condition on comboBox. Following is the code and Output. Please help me, as I have to show this to my instructor tomorrow.
public ArrayList<User> userList() {
ArrayList<User> usersList = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(url);
String query = "SELECT * FROM tbl_Income";
Statement st=con.createStatement();
ResultSet rs= st.executeQuery(query);
User user;
while(rs.next()){
user= new User(rs.getInt("Amout"),rs.getString("Date"),rs.getString("Source"));
usersList.add(user);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return usersList;
}
public void show_user() {
ArrayList<User> list = userList();
DefaultTableModel model = (DefaultTableModel)Income_Table.getModel();
Object[] row =new Object[3];
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getAmout();
row[1]=list.get(i).getDate();
row[2]=list.get(i).getSource();
model.addRow(row);
}
}
//**********tbl_Expense
public ArrayList<User_E> userList_E() {
ArrayList<User_E> UsersList_E = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String eurl="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(eurl);
String query_E = "SELECT * FROM tbl_Expense";
Statement stt=con.createStatement();
ResultSet rst= stt.executeQuery(query_E);
User_E user_e;
while(rst.next()){
user_e = new User_E(rst.getString("ExpenseDetail"),rst.getString("Category"),rst.getString("Date"),rst.getInt("Amount"));
UsersList_E.add(user_e);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return UsersList_E;
}
public void showuser_E(){
ArrayList<User_E> list_E = userList_E();
DefaultTableModel model_e = (DefaultTableModel)Expense_Table.getModel();
Object[] row_e =new Object[4];
for(int i=0;i<list_E.size();i++){
row_e[0]=list_E.get(i).getAmount();
row_e[1]=list_E.get(i).getDate();
row_e[2]=list_E.get(i).getCategory();
row_e[3]=list_E.get(i).getExpenseDetail();
model_e.addRow(row_e);
}
}
This is the Output, getting 0 instead of original data
I cannot tell what the issue by looking at the code posted. But, the application's database access, querying and showing the data in the GUI need to be structured something like this:
1. Access database and get connection:
Get connection object for the database DB_Project (there is no need to create connection objects twice).
2. Query 1:
Create statement
Query the tbl_Income table and populate the "userList"
Close the statement (this also closes the corresponding result set)
3. Query 2:
Create statement
Query the tbl_Expense table and populate the "userList_E"
Close the statement
4. Close connection (this is optional and depends on application requirement).
5. Display GUI using the queried data:
Show user income JTable using the "userList"
Show user expense JTable using the "userList_E"
NOTES:
Place some debug or log statements in the Java code and verify if there is any data in the tables being queried and also what kind of data it is. Querying the database tables directly and interactively or from the command prompt also helps. Also, after populating the list collections print the lists onto the console using System.out.prinltln() statements to verify if the data is populated to them properly.
How to display based on combo box selection:
Here is the link to Java tutorials on using Swing JComboBox - see the section "Handling Events on a Combo Box".
There are different ways one can build the code to acheive this functionality.
By directly querying the database table using the data selected from
the combo box, or
By filtering the data from the "list" data already queried and populated to it. This option requires the queried data from the database tables be stored in instance variables.
Again, it depends upon the application requirement. In case the database table data is not changing then option 2 is the correct method, otherwise query the database table directly.
One hideous thing: nothing is closed (connection, statement, result set).
Try-with-resources may help here, to automatically close those, even on return, break, raised exception.
public ArrayList<User_E> userList_E() {
ArrayList<User_E> usersList_E = new ArrayList<>();
String eurl = "jdbc:sqlserver://localhost:1433;databasename=DB_Project;"
+ "user=User;Password=password";
String query_E = "SELECT * FROM tbl_Expense";
try (Connection con = DriverManager.getConnection(eurl);
Statement stt = con.createStatement();
ResultSet rst= stt.executeQuery(query_E)) {
while(rst.next()){
User user_e = new User_E(rst.getString("ExpenseDetail"),
rst.getString("Category"),
rst.getString("Date"),
rst.getInt("Amount"));
usersList_E.add(user_e);
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
return usersList_E;
}
Class.forName on the driver class is since years no longer required.
For the error: I can only assume that the application is running out of free connections.
I've a table in database named customer that have attribute like code and name. I've called the value of the customer in other table and displayed it using combo-box. I've displayed the code in combo-box, and all I wanna do is when I choose the code in combo-box, value 'name' can be displayed in text-field , the 'name' appear based on code.
here is my code :
try {
Connections con = new Connections();
con.setConnections();
String sql = "select * from customer";
Statement stat = con.conn.createStatement();
ResultSet rs=stat.executeQuery(sql);
while (rs.next()){
cmb_custCode.addItem(rs.getString("custCode"));
txt_custName.setText(rs.getString("custName")); // i'm confused in here, how can i call the name based on the code
}
}
catch(Exception e){
e.printStackTrace();
}
}
for example :
when the code 'B0001' is selected in the combobox, the Jtextfield must also display "Bob" , because code B0001 is belongs to Bob.
EDIT:
Ok. So let's say that you have a user Bob and his code is B001.
ItemStateChanged Method
...
String code = (String) cmb.getSelectedItem();
try{
String sql = "SELECT * FROM customer WHERE code='"+code"'"
PreparedStatement prst = con.prepareStatement();
ResultSet rs = prst.executeQuery(sql);
String name = "";
while(rs.next()){
name = rs.getString('name');
}
txt.setText(name);
}catch(Exception ex){
}
You shouldn't actually connect inside the itemStateChanged but this is just an example.
Take a look at this article. It tells you everything you need to know on how to use combo boxes.
http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
In your own example code, you can declare the enclosing class as an ActionListener. then use the following after declaring your cmb_custCode
...
cmb_custCode.addActionListender(this);
...
when implementing an ActionListener, you have to implement the method actionPerformed(). I've cribbed the following from : http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#listeners but adapted to your code
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String custCode = (String)cb.getSelectedItem();
updateLabel(custCode);
}
I've maintained the encapsulation of updateLabel(String custCode) from the example on the trail. You can assume that that method is defined as something like :
private void updateLabel(String code) {
txt_custName.setText(map_cust.get(code));
}
I've brough a Map into it with map_cust. It's just a map between code and name, stored in a field
Map<String, String> map_cust = new HashMap<String, String>();
and populated it, this would go in your code, just after retrieving the ResultSet
...
cmb_custCode.addItem(rs.getString("custCode"));
map_cust.put(rs.getString("custCode"), rs.getString("custName");
So, when you get your result set, you populate a map and your combo box, when the client picks and item from the combo box, he fires and actionPerformed, into the registered listener, where the event is manipulated to get the selected item, the String of which is the key to the map_cust, containing mapped key, value pairs, custCode mapped to custName. When that name is pulled from the map, it may be used to update the text of the label.
Here is my code, and it solved my problem. Hope it's useful for you too :).
private void fillText(){
String code = (String) cmb_custCode.getSelectedItem();
try {
Connections con = new Connections();
con.setConnections();
String sql = "select * from customer WHERE custCode='"+code +"'";
Statement stat = con.conn.createStatement();
ResultSet rs=stat.executeQuery(sql);
while (rs.next()){
txt_custName.setText(rs.getString("custName"));
}
}
catch(Exception e){
e.printStackTrace();
}
Hy! I am working on my Java MySql app, and I need to save data about meals that are stored on my database on server, so I can later display it in combobox. User will choose what meal he wants in combo-box and when he presses "confirm" button, it will execute query about his order.
So basiclly, each meal (row) in my server database table consists of id_category (id_kategorija), id_meal (id_jela), name_of_meal (naziv_jela). Should I use HashMap for this ? If it's possible to do, how to save all that data in one Hash-Map so I can later easily make query by using that HashMap ?
Here is picture of my database table for meals:
Here is my code:
String queryZaJela;
Map <Integer,String>PopisJela = new HashMap<Integer, String>();
try {
queryZaJela="SELECT id_kategorija, naziv_hrane FROM `naziv_jela`";
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://"
+ "localhost:3306/room_service", "root", "");
Statement Stat = (Statement) con.createStatement();
ResultSet Rez = Stat.executeQuery(queryZaJela);
while (Rez.next()) {
PopisJela.put(Rez.getInt("id_kategorija"), Rez.getString("naziv_hrane") );
}
PopisJela.put(0,"Select");
Rez.close();
Stat.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
I can suggest you to have a small class to save all 3 values from database and to put the objects to that class against the id_jela or id_kategorija according to your query in future.
public class mealStruct {
public int id_kategorija;
public int id_jela;
public string naziv_hrane;
}
and when you read data from database, make an object to mealStruct class and put it in the map against the id of your need.
//here is the HashMap of id_kategorija/id_jela and mealStruct.
//Keep filling hashMap with id and the object. when the user selects a meal from combo,
//get the id and access the object from mealStruct and get all 3 values to use in query.
<Integer,String>PopisJela = new HashMap<Integer, mealStruct>();
i know this should be simpel and im probably staring straight at the problem but once again im stuck and need the help of the code gurus.
im trying too take one row from a column in jdbc, and put them in an array.
i do this as follows:
public void fillContactList()
{
createConnection();
try
{
Statement stmt = conn.createStatement();
ResultSet namesList = stmt.executeQuery("SELECT name FROM Users");
try
{
while (namesList.next())
{
contactListNames[1] = namesList.getString(1);
System.out.println("" + contactListNames[1]);
}
}
catch(SQLException q)
{
}
conn.commit();
stmt.close();
conn.close();
}
catch(SQLException e)
{
}
creatConnection is an already defined method that does what it obviously does.
i creat my result set
while theres another one,
i store the string of that column into an array.
then print it out for good measure. too make sure its there.
the problem is that its storing the entire column into contactListNames[1]
i wanted to make it store column1 row 1 into [1]
then column 1 row 2 into [2]
i know i could do this with a loop. but i dont know too take only one row at a time from a single column. any ideas?
p.s ive read the api, i jsut cant see anything that fits.
You should use an ArrayList which provides all the logic to automatically extend the array.
List rowValues = new ArrayList();
while (namesList.next()) {
rowValues.add(namesList.getString(1));
}
// You can then put this back into an array if necessary
contactListNames = (String[]) rowValues.toArray(new String[rowValues.size()]);
Did you mean something like:
int i = 0;
ResultSet rs = stmt.executeQuery("select name from users");
while (rs.next()) {
String name = rs.getString("name");
names[i++] = name;
}