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.
Related
Here's my code for the addStudent:
#FXML
private void addStudent(ActionEvent event) {
// sql query to insert data into students at ID, first name, last name, email and DOB
String sqlInsert = "INSERT INTO students(id,fname,lname,email,DOB) VALUES (?,?,?,?,?)";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sqlInsert);
// add the data in the right column
stmt.setString(1, this.id.getText());
stmt.setString(2, this.firstname.getText());
stmt.setString(3, this.lastname.getText());
stmt.setString(4, this.email.getText());
stmt.setString(5, this.dob.getEditor().getText());
stmt.execute();
conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
And here's my code for removeStudent:
#FXML
private void removeStudent(ActionEvent event) {
try {
// sql query to delete data from the database
String sqlRemove = "DELETE FROM students WHERE id = ?";
// open a connection to the database and use PreparedStatement to
// initialize the query.
Connection conn = dbConnection.getConnection();
PreparedStatement delete = conn.prepareStatement(sqlRemove);
// information needed to delete the row
delete.setString(1, selectStudent());
// execute and delete
delete.executeUpdate();
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// update table after deleting
loadStudentData(event);
}
The picture above is the view of my table. I hit LoadData and my table values show up. I want to be able to click on a row(student) and hit Delete Student to remove it.
Helper method for removeStudent:
private String selectStudent() {
String result = "";
try {
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
result = rs.getString(1);
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return result;
}
I'm pretty sure it has to do with when I "click" on a row, the id value for that isn't being held anywhere so when I hit "Delete" nothing is being given for it to Delete.
I don't know. Any advice would be awesome. :D
First edit: nothing is assigned to delete.setString(1, this.id.getText()). When I click on the row and hit delete, nothing is happening because there's nothing being assigned to id when I click on the row. The query string DOES work however when I physically give it an ID to delete. Also verified that the button does work; it prints out a lovely message for me with a good ol' System.out.println("expletive");
Second edit: Ok, so I updated the removeStudent code and now all I get is the string "null" returned. Nothing deletes. Nothing updates. Nothing is happening except I get "null" in the console.
Third edit: Getting closer! With the realization that the removeStudent isn't being given an ID to delete, I decided to create a private helper method that will do a SELECT query. Now, when I hit delete, it'll delete....but from the top, and not at where I want it selected. The code is above.
Fourth edit: Getting even closer! So, I figured out how to capture the row I click on within the table and I can delete......however, because of my sqlRemove command, I'm deleting by id so if I click on a row with index 3, then ONLY the row within the table that has an id of 3 will be deleted, nothing else. I gotta re-write how the sqlRemove command is worded.
I fixed it:
private String selectStudent() {
// initial value for result to return
String result = "";
// grab the index of the row selected on the table
int initial = studenttable.getSelectionModel().getSelectedIndex();
try {
// SELECT query to execute
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
// while there's a next row
while(rs.next()) {
// set temp to equal the id rs.next() is currently on
String temp = rs.getString("id");
// get the row id - 1 since we start at 0
int temp1 = rs.getRow() - 1;
// if temp1 is equal to the index we selected
if(temp1 == initial) {
// make it equal to result
result = temp;
}
}
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// return the row to delete
return result;
}
What's going on is in the comments. I finally figured out how to pass the value from a selected row and compare it to a row. Once I get the correct row to pass, I give it to the delete function to remove.
After a day in a half.............but I love it, so. Yeah.
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.
I have a mysql table user which is consisted of id, name, password and email columns.
Is there a way to create some sort of query or java code that will print in my message dialog window all of the users names.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
val1 = rs.getString(2);
val2 = rs.getString(3);
}
value = val1 + " " + val2;
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
This only prints the name and the surname of the first user from the table :(
I want to print them all one below another!
If I set rs.getString(5); - it gives me an error: column index out of range.
I suggest you avoid JOptionPane for this kind of code. Better to use some Frame (Swing) and display all of the users into a separate window.
The problem with your code is that variable value is lyiong outside of the loop (which must be btw while loop, as spencer said).
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
val = rs.getString(2) + " " + rs.getString(3);
value += val + " ";
}
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
Try to avoid this type of code, use ArrayList and save in the array all of the users credentials. Then easily label it wherever you want.
You're only fetching the first row from the resultset. It sounds like you want a loop, and process every row from the resultset.
while (rs.next()) {
}
UPDATE
Q: It only gives me now the last user. Probably because it overwrites the val1 and val2 variable. I suppose somehow this should also goes into the loop..
A: Yes, it should go inside the loop. But I'd be populating a collection, rather than concatenating a String.
As a performance and maintenance note, you can avoid the messiness of the string concatenation in the Java by doing the concatenation in the SQL statement. I wouldn't use SELECT * and rely on the positions of two particular columns in the resultset.
I'd use a SQL statement like this:
SELECT CONCAT(u.first_name,' ',u.last_name) AS user_name FROM users
If I wasn't populating a collection, and I needed to concatenate a honkous string, I'd use a StringBuffer, e.g.
val = new StringBuffer(4096));
while (rs.next()) {
val.append(rs.getString("user_name"));
}
value = val.toString;
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();
}
I am working in a project known as Employee attendance management system.For this I had created a java form.The form contains employee ID,employee name fields,next button.
If I press next button the next employee details has to be displayed in the above two fields.In order to do this I had used for loop the problem hear appears is it is displaying last employee details from the database.
My code is:
int i=1;
try {
ResultSet rs;
Connection con;
Statement st;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:vasu");
st = con.createStatement();
for(i=1;i<=5;++i){
rs = st.executeQuery("select ID,EName from attendence where ID="+(i));
while(rs.next()) {
t1.setText(rs.getString("ID"));
t2.setText(rs.getString("EName"));
}
}
}
catch (Exception e) {
}
Sorry for my poor english.
Could any one please help me..
Well Thanks in advance.
There is problem in this loop
while(rs.next()) {
t1.setText(rs.getString("ID"));
t2.setText(rs.getString("EName"));
}
you need to store the values from database in an array and then iterate over it with your (prev,next) button like
i=0;
while(rs.next()) {
dataset["id"][i]=(rs.getString("ID");
dataset["EName"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
t1.setText(dataset["id"][i]);
I have not checked syntax but the logic is correct.
The values are being overwritten each time in t1 and t2 when you call the loop. This is why the last record value is being displayed.