how to display results on label with sql - java

UPDATE
i changed sql query (just test it and it works on sql but still not working with java dont no why :(
Hi how to add get result on jLabel with this code? and is it possible to show results on jTable?
private void searchTeacherActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = ("select student_ID, firstName, afterName FROM student JOIN studentHom ON course = studentHom_ID WHERE prefect = ?
try {
pst = connection.prepareStatement(sql);
pst.setString(1, larareSoka.getText());
pst.execute();
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
}

First don't use (?) you can just use ?:
select ... where course.courseStart = ? and course.corse.end = ?
Second you have to set parametters to your query in your case you have tow, so you have to use :
pst.setString(1, value_of_courseStart);
pst.setString(2, value_of_corse.end);
Third to get results you have to use ResultSet like this :
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString(1);
//----------------------------------^
//...same for the other columns
}
or you can use the name of column like this:
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString("firstName");
//--------------------------------------^^
//...same for the other columns
}
Note
If you want to get multiple result you ca use while instead of if.
Your query is a little wired why you are using :
course.courseStart = (?) and course.corse.end = (?)
//no point---^ ^------Why this point here
Did you mean course.courseStart = ? and course.corseEnd = ?

ResultSet rs = pst.executeQuery();
String firstname = rs.getString("firstname");
..
jLable.setText(firstname);
...You need to read the data from the resultset

Related

How to use Resultset?

I am using a mysql table, and now I need to compare a columns all values with a given String.
I want to check if all values of the result set matches with encryptedString.
Need to understand what result set does and how it works.
Here I have a method, Some variables, and 2 mysql queries.
final String secretKey = "!!!!";
String name = jText.getText();
String pass = jTextPass.getText();
String originalString = pass;
String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;
PreparedStatement PS;
ResultSet result;
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` =?";
PreparedStatement ps;
String query;
query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`=?";
try {
PS = MyConnection.getConnection().prepareStatement(query1);
PS.setString(1, name);
PS.setString(2, encryptedString);
rs = PS.executeQuery();
//while(result.next() ){
//I am not understanding what to do here.
ps = MyConnection.getConnection().prepareStatement(query);
ps.setString(1, encryptedString);
ps.setString(2, name);
ps.executeUpdate();
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
this.dispose();
//}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
}
First tip: using try-with-resources closes statement and result set even on exception or return. This also reduces the number of variable names for them because of the smaller scopes. This return from the innermost block I utilized. For unique names one can use if-next instead of while-next. A fail-fast by not just logging the exception is indeed also better; you can exchange the checked exception with a runtime exception as below, so it easier on coding.
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` = ?";
String query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`= ?";
try (PreparedStatement selectPS = MyConnection.getConnection().prepareStatement(query1)) {}
selectPS.setString(1, name);
//selectPS.setString(2, encryptedString);
try (ResultSet rs = selectPS.executeQuery()) {}
if (result.next()){ // Assuming `name` is unique.
String pass = rs.getString(1);
try (PreparedStatement ps = MyConnection.getConnection().prepareStatement(query)) {
ps.setString(1, encryptedString);
ps.setString(2, name);
int updateCount = ps.executeUpdate();
if (updateCount == 1) {
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
return success;
}
}
}
}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException(e);
} finally {
dispose();
}
the ResultSet object contains all the information about the query that you perform, it will contain all columns. In your code the result variable will return anything since there is no part in your code where is executed, to do this you have to...
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
while(result.next()){
String column1 = result.getString("columnName");
}
The result.next() method is a boolean method that says if the ResultSet object still have values of the table inside and it will continue until it reaches the last row that your SELECT statement retrives. Now if you want to match the value of some column with other variables you can do it inside the while(result.next()).
result.getString("columnName") will extract the value from columnName as a String.
If you want to save things in an ArrayList to save the data and then use this list as you want the code can be like...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
List<Object> data = new ArrayList();
while(result.next()){
data.add(result.getString("columnName"));
}
return data;
Obviously you have to change the Object with the type of things that you want to store in the List.
Or if you want to store the data in an array. As I said in my comment this won't be dinamic, but...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
String[] data = new String[NUMBER_OF_COLUMNS_IN_RESULTSET];
while(result.next()){
data[0] = result.getString("columnName1");
data[1] = result.getString("columnName2");
data[2] = result.getString("columnName3");
//And so on...
}
return data;
The other way is that if you are returning an entity you can set the values of the ResultSet directly in the POJO:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
Entity entity = new Entity();
while(result.next()){
entity.setColumnName1(result.getString("columnName1"));
entity.setColumnName2(result.getString("columnName2"));
entity.setColumnName3(result.getString("columnName3"));
//And so on...
}
return entity;
There are so many ways to store the data, just ask yourself how do you want to receive the data in the other parts of you code.
Regards.

find a name in a sqlite table and return the id?

What I'm trying to do seems simple but I get this error SQLITE_ERROR] SQL error or missing database (no such column: user1)
public String getIdUser(String name) {
try {
this.stat = conn.createStatement();
String sql = "SELECT id_user FROM User WHERE name = " + name;
ResultSet user = stat.executeQuery(sql);
return user.toString();
} catch (SQLException e) {
return null;
}
}
Replace
String sql = "SELECT FROM User WHERE name = " + name;
with
String sql = "SELECT * FROM User WHERE name = " + name; // you can also specify a column/columns instead of *
I see many problems in your code :
First
Your query should return something it should be :
SELECT col_name1, col_name2, ... FROM User ...
Or if you want to select every thing :
SELECT * FROM User ...
Second
String or Varchar should be between two quotes, your query for example should look like :
SELECT col_name1 FROM User WHERE name = 'name'
Third
I don't advice to use concatenation of query instead use Prepared Statement it is more secure and more helpful (I will provide an example)
Forth
To get a result you have to move the cursor you have to call result.next()
Fifth
Name of variable should be significant for example ResultSet should be ResultSet rs not ResultSet user
Your final code can be :
PrepareStatement prst = conn.prepareStatement("SELECT colName FROM User WHERE name = ?");
prst.setString(1, name);
ResultSet rs = prst.executeQuery();
if(rs.next()){
reuturn rs.getString("colName");
}
Without quoting the name string it's interpreted as column name, and thus the error you see. You could surround it with single quotes, but that's still generally a bad practice, and will leave the code vulnerable to SQL injection attacks.
Additionally, you're missing the select list (specifically, the id_user column), and missing getting it from the result set.
And finally, you forgot to close the statement and the result set.
If you put all of these corrections together, you should use something like this:
public String getIdUser(String name) {
try (PreparedStatmet ps =
conn.prepareStatement("SELECT id_user FROM User WHERE name = ?")) {
ps.setString(1, name);
try (ResultSet rs = stat.executeQuery()) {
if (rs.next()) {
return rs.getString(1);
}
}
} catch (SQLException ignore) {
}
return null;
}

Can't print information from SQL in Java

The user must choose a Resort ID from the table that is displayed and the make a booking. I can't seem to find my problem, I want to print the name of the Resort that they are making a booking at.
String x = jTextFieldID.getText();
Integer Resort = Integer.valueOf(x);
int resort = Integer.parseInt(x);
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+Resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
You have to use rs.next() :
ResultSet rs = pstmt.executeQuery(sql);
String resortName = "";
if(rs.next()){//<<-----------------------------
resortName = rs.getString("RESORT_NAME");
}
JOptionPane.showMessageDialog(null, "You want to book at "+resortName);
If you want to get many results you can use while(rs.next){...} instead.
Note? for a good practice, don't use upper letter in beginning for the name of your variables ResortName use this instead resortName
You need to test over the ResultSet result before trying to read from it:
if(rs.next()) {
String ResortName = rs.getString(1);
JOptionPane.showMessageDialog(null, "You want to book at "+ResortName);
}
And you can use getString(1) to get the RESORT_NAME, check ResultSet .getString(int index) method for further details.
The error is that sql is passed to Statement.executeQuery(String) too, instead of the PreparedStatement.executeQuery().
int resort = Integer.parseInt(x);
//String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = ?";
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = " + resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
//pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
}
} catch (SQLException ex) {
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}
Commented is the alternative usage of a prepared statement (as normally used).
Also you should close statement and result set, which can be done automatically with try-with-resources as above.
Oh, oversaw almost, that rs.next() must be called. (The others already mentioned.)

How to use select count on my database

private void Update_table(){
try {
String sql= "select Firstname, Lastname,ID_number from regmembers";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
jTable_regMembers.setModel(DbUtils.resultSetToTableModel(rs));
jTable_regMembers.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTable_regMembers.getTableHeader().setReorderingAllowed(false);
jTable_regMembers.getTableHeader().setResizingAllowed(false);
} catch(Exception e){
JOptionPane.showMessageDialog(null, e+"");
}
}
how can i display the data of registered members of my database and put it into jtextfield, newbie question?
iterate over the resultset object and set the values obtained
ResultSet resultSet = ps.executeQuery();
if (resultSet.next()) {
do {
// perform your logic
yourTextfield.setText(rs.getString("yourColumnName"));
} while(resultSet.next());
You should be able to execute a simple query and use the value in the Result set to set your textfield.
String sql = "Select count(*) from regmembers";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
textfield.setText(rs.getInt(1));
Hope this works the way you wanted it to

compare database column values in mysql with another String in java

I have a database with the following layout
databasename:macfast
table name:users
columns
id,
user_name,
password,
fullName
I want to retrieve all the values from the column user_name and check each values with another one string which is already retrieved from a TEXTFIELD.But I can't(NullpointerException). Please help me.
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username=removeText.getText();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
String check=(rs.getString("user_name"));
System.out.println(check);
if(check.equals(username)){
Util.showErrorMessageDialog("EQUAL");
}else{
Util.showErrorMessageDialog("NOT EQUAL");
}
}
}catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
Problem is with the prepared statement (you don't put id into statement, which should be there instead of question mark).
Also I would recommend to do condition as "username.equals(check)", that can prevent null pointer exception.
"SELECT user_name From users where id=?"
This query has a parameter and you're not setting any value to it. Use PreparedStatement#setInt() or similar to set it, e.g.:
stmt.setInt(1, 1);
The problem is with PreparedStatement as you are using Question mark ? in your query for that you have to set the Id value.
String qry = "SELECT user_name From users where id=?";
stmt = (PreparedStatement) connection.prepareStatement(qry);
stmt.setInt(1,1001);
rs = stmt.executeQuery();
For your question in comment below:
List<String> values = new ArrayList();
while (rs.next()) {
values.add(0,rs.getString(<>))
}
// here do whatever you want to do...
// for example
for ( String value: values )
{
// check if value == TEXTFIELD
// if true then do something..
// else don't do anything
}

Categories

Resources