i wanted to retrieve the data from the database with ID.. So, i wanted to do like this: i have number on my combobox 1 to 4. Whenever i select 1 in combobox, the textbox firstname and lastname text will be change based on the selected id. How do i do that?
I already tried like this, but it won't work:
private void Edit(Connection conn, Statement state, ResultSet result)
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String url = "jdbc:odbc:Database";
conn = DriverManager.getConnection(url);
String query = "select FirstName, LastName, Status, JoinedDate from Customer where ID = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, jComboBox1.getSelectedIndex());
result = statement.executeQuery();
while(result.next())
{
jTextField3.setText("FirstName");
jTextField2.setText("LastName");
jTextField3.setText("Status");
JoinedDateLabel.setText("JoinedDate");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
_sound.PlaySound(2);
_infoBox.ShowMessageBox(e.getMessage(), "Error", 2);
_reminder = new Reminder(1);
JOptionPane.showOptionDialog(null, "Program will be closed due to error!", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
System.exit(0);
}
Thank you
Try this
while(result.next())
{
jTextField1.setText(result.getString("FirstName"));
jTextField2.setText(result.getString("LastName"));
jTextField3.setText(result.getString("Status"));
JoinedDateLabel.setText(result.getString("JoinedDate"));
}
All you're doing with your current code is setting the text to the strng literal "FirstName". You need to actually retrieve the data from the ResultSet and set the text as that data.
Also, note JComboBox indices are 0 based. So if you are selecting the first index, it would return 0. You should make sure (in your case) that the db has Id's of 0,1,2,3
Related
I am working on java swing project with database. There is a search by option (dropdown) to select by which attribute the user want to search and very next to dropdown their is a textfield where user can enter value and then click search. now i want to search for that particular value in that particular column(which is selected by user through the dropdowm) if it is exits i want to print them "found" if not then i want to display not found message.. Please find the attached images & code below.
For example: from dropdown if user select 'customer id' which is a column name and they enter id in the textfiled as '123456' then if it is exits in the column then i need to print found message else i need to print not found.
String column = jcombo2.getSelectedItem().toString();
String value = key.getText();
DefaultTableModel model = (DefaultTableModel) customerinfo.getModel();
DefaultTableModel model2 = (DefaultTableModel) customerinfo.getModel();
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs =st.executeQuery(mysqlQuery);
while(rs.next()) {
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
Try this:
String mysqlQuery = "SELECT COUNT(*) FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
if (rs.next() && (rs.getInt(1) != 0))
printFoundIt(); // or whatever you want to do
else
printDidntFindIt(); // or whatever you want to do
st.close();
Or in case you want to fill the table with found items contemporarily:
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
boolean found_it = false;
while (rs.next())
{
found_it = true;
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
st.close();
if (found_it)
printFoundIt(); // or whatever you want to do
else
printDidntFindIt(); // or whatever you want to do
Same as before but printing the 'found it' directly after having found the first element:
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
boolean found_it = false;
while (rs.next())
{
if (!found_it)
{
printFoundIt(); // or whatever you want to do
found_it = true;
}
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
st.close();
if (!found_it)
printDidntFindIt(); // or whatever you want to do
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 am trying to make a username only register if that name is not taken, using JDBC connection and checking on SQL Database.
I have the code that checks for the
SELECT * FROM user
WHERE username = 'jessica';
and it finds 2 rows;
Searched a lot and found that with getFetchSize() it would give me the number of rows, and if it finds null it would return 0.
It is always returning 0, I don't know why, because I have the usernames taken twice, it lets me add me always...
https://prnt.sc/galyqo
public int nameAvailable(MyUserApp app, String name) throws SQLException{
String sql = "SELECT * FROM user \n WHERE username = '"+ name +"';";
Statement st = app.getCon().createStatement();
ResultSet rs = st.executeQuery(sql);
int numResults = rs.getFetchSize();
return numResults;
}
This is the register code:
private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {
String username, password, address, dob;
boolean status;
String u;
try {
username = newUsernameField.getText();
password = passwordField2.getText();
address = addressField.getText();
dob = dateofbField.getText();
int no= 5;
if( username.isEmpty() || password.isEmpty() || password.length() < 6 ){
jLabel6.setText("The information you typed in is not valid. ");
status = false;
showTableDB.setText(""+status);
}
else{
no = this.app.nameAvailable(app, username);
jLabel6.setText(no+"");
if(no == 0){
jLabel6.setText("Registered your account, "+username+"!" + no);
status = this.app.registerUser(app, username, password, dob, address);
u = this.app.showInfo(app, username);
showTableDB.setText(u);
no = this.app.nameAvailable(app, username);
}
else{
showTableDB.setText("That username is token. Please choose a different one.");
}
}
} catch (SQLException ex) {
Logger.getLogger(UserAppUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(UserAppUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Resolved. Solution:
public int getNCount(MyUserApp app, String name) throws SQLException{
String sql = "SELECT COUNT(*) FROM user \n WHERE username = '"+ name +"';";
int rowCount;
PreparedStatement st = app.getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet r = st.executeQuery(sql);
r.next();
// get the number of rows from the result set. On the db it will show a table with "count(*)" and the #counts
rowCount = r.getInt("count(*)");
r.close();
st.close();
return rowCount;
}
By calling these statement on the code:
r.next()
and then
rowCount = r.getInt("count(*)");
I was able to get the 2nd column of the count(*) SQL Statement.
The fetch size is not the same thing as the number of rows. The fetch size is just a way of limiting how many rows at a time will be fetched from the database.
There's no easy way to check the number of rows returned by a select statement. If you really need to know how many rows there are, in the case there's more than one, then one approach would be to iterate through the result set, copying the information that you need from each row into memory; then check the amount of data that you copied at the end.
Alternatively, if you don't actually need any data from the rows themselves, you could try a statement like SELECT count(*) FROM user WHERE username = ?.
One more thing - you need to read about SQL injection attacks. This is where a hacker uses your code to run SQL that they shouldn't. The code you've shown here is vulnerable to an SQL injection attack. But that's another question entirely.
Resolved. Solution:
public int getNCount(MyUserApp app, String name) throws SQLException{
String sql = "SELECT COUNT(*) FROM user \n WHERE username = '"+ name +"';";
int rowCount;
PreparedStatement st = app.getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet r = st.executeQuery(sql);
r.next();
// get the number of rows from the result set. On the db it will show a table with "count(*)" and the #counts
rowCount = r.getInt("count(*)");
r.close();
st.close();
return rowCount;
}
By calling these statement on the code:
r.next()
and then
rowCount = r.getInt("count(*)");
I was able to get the 2nd column of the count(*) SQL Statement.
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.
For example:
If TextField1 == to the data in the database.
Output: Swept by GSW.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list WHERE id = ?";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
}
}
}catch(SQLException exc){
System.out.println("Not Found!");
}
Kindly Check the Image Output.
I attached the image file below.
Sample Output
Here are some mistake I see
You use a parameter in the query, "SELECT * FROM item_list WHERE id = ?";so use a PreparedStatement
Set the parameter to that PreparedStatement ps = connection.preparedStatement(query); with ps.setInt(1, Integer.parseInt(TF[0].getText()));
Don't catch the exception without logging it, here your query as a syntax error but you don't know it.
careful with uppercase in the database field name "Id"
This might not be everything ...
And of course, now that you get only the row with that ID, you can simply check if there is at least one row return to validate that it exists.
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.
Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.
PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT
You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.
you can use intValue() for Integer object obvious if your object is not null
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()).intValue() == id){
System.out.println(id);
}
}
You're not setting the value of the id parameter in the statement. Not familiar with Java but in C# it would be something like
statement.Parameters.AddWithValue("#id", id)
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.
Appreciated all your help.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
JOptionPane.showMessageDialog(null, "FOUND!");
}
else{
JOptionPane.showMessageDialog(null, "Not Found!");
}
}
}catch(SQLException exc){
JOptionPane.showMessageDialog(null, exc.getMessage());
}
ID Found!
I am trying to display data from the database into a datatable and I am getting no results. I tested the queries with JDBC with exact select statement to see if it returns any row, and it always worked. But when I try to have the data from the database into my datatable I get no results. I even made a fake dummy data just to populate my datatable. I must be doing something wrong in the index.xhtml file that I don't know of. What could I doing wrong ? any help would be appreciated ?
edit: first I went to with Primefaces with their datatable example, and than I went with simple jsf style datatable like I have here and neither of those worked when I try to do it with the database
UserDAO.java
public class UserDAO {
private static final String USERNAME = "something";
private static final String PASSWORD = "something";
private static final String CONN_STRING =
"jdbc:sqlserver://petunia.arvixe.com.....something";
public List<Report> getUserList() {
List<Report> list = new ArrayList<Report>();
PreparedStatement ps = null;
Connection con = null;
ResultSet result = null;
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
while (result.next()) {
Report rep = new Report();
rep.setId(result.getInt("id"));
rep.setTag(result.getString("tag"));
rep.setName(result.getString("asset_name"));
rep.setModel(result.getString("model"));
rep.setSerial(result.getString("ser_no"));
rep.setValue(result.getFloat("value"));
rep.setCondition(result.getString("asset_condition"));
rep.setType(result.getString("asset_type"));
rep.setLocationName(result.getString("name"));
rep.setAddress(result.getString("address"));
rep.setCity(result.getString("city"));
rep.setState(result.getString("state"));
rep.setZip(result.getString("zip"));
rep.setPhone(result.getString("phone"));
rep.setDistrict(result.getInt("district"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
Well, you are making a report:
Report rep = new Report();
...but not adding it to your list. Add this:
Report rep = new Report();
list.add(rep);
I suppose your problem is this code:
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You are overwriting your sql statement immediately with the statement sql1.
I think, you probably want to select the assets with THEIR locations. In SQL you can use a JOIN to achieve that.
If you use this syntax
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You will get as a result only the execution of the second query. I think that in your case you are trying to get a result from both tables assets and location so you should use a join between the 2 tables.