Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
try {
setPassword(txtPassword.getText());
setUsername(txtUserName.getText());
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte messgeDigest[] = md.digest(getPassword().getBytes());
BigInteger number = new BigInteger(1, messgeDigest);
String hashtext = number.toString(16);
String qry = "SELECT * FROM users WHERE username=? AND password=?";
pst = mscon.conn().prepareStatement(qry);
pst.setString(1, getUsername());
pst.setString(2, hashtext);
rs = pst.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Login Successful");
System.out.println("Login");
}
else{
System.out.println("Tri again");
}
} catch (NoSuchAlgorithmException ex) {
} catch (SQLException ex) {
Logger.getLogger(MS_Login.class.getName()).log(Level.SEVERE, null, ex);
}
In this code the if(rs.next) part does not work. I tried to print some word in that block but it does not show up. Whats is problem?
rs.next() attempts to retrieve the next row. If a row is returned true is returned, if there are no more rows false is returned.
Clearly, your query is not returning any rows.
Debug your program to show the values of your parameters (either by running in debug mode, or simply printing the values to stdout).
rs.next() will return if there is any records present in your resultset. It is not working for you because your resutset is empty. Try debugging your and check what is the result of the query that you are executing.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Problem Image
String connectionUrl = "jdbc:sqlserver://localhost;databaseName=QLSV;user=sa;password=12345";
try (Connection con = DriverManager.getConnection(connectionUrl);
Statement stmt = con.createStatement();) {
String SQL = "SELECT TOP 10 * FROM USERS";
ResultSet rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString("USERNAME") + " " + rs.getString("PASSWORD"));
}
} // Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
if the project is maven please update the following dependency
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.1.jre11</version>
</dependency>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
when am running my action i faced Error :
" java.util.ArrayList cannot be cast to java.lang.String "
and this is my code :
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selected = list_1.getSelectedValue();
Connection conn = null;
PreparedStatement stmt = null;
String a =null;
try{
conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
String query= " INSERT INTO flyer_item (discount) SELECT price * ? FROM `item` WHERE item_name = `?` ";
Statement st= conn.createStatement();
java.sql.PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,a);
ps.setString(2,(String) selected);
ps.executeUpdate();
st.executeUpdate(query);
} catch (SQLException se){
System.out.println(se.getMessage());
} }} );
Any help please ?
Here Selected is an array-list and you are trying to convert it into string which is not possible:
ps.setString(2,(String) selected);
What you should do?
ps.setString(2, selected.tostring());
Are you sure about this line ?
Object selected = list_1.getSelectedValue();
Make sure selected is a String before casting . You can use instanceof operator to check the Object type.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to create a sql sequence in sql server programmatically from Java and I should be able to retrieve the continuous value from the sequence to program. First of all can I do so? If so how?
It's possible as all SQL servers provide some functionality and guarantee ACID rules. Even with very simple old MySql engine which didn't support transactions it's achievable. The easiest and widely supported approach is:
CREATE TABLE SequenceValue (
sequenceIdentifier varchar(124) NOT NULL PRIMARY KEY,
sequenceValue INT NOT NULL;
);
All you need to do in the program is:
Connection con = dataSource.getConnection();
try {
con.setAutoCommit(true);
PreparedStatement st = con.prepareStatement("SELECT sequenceValue SequenceValue WHERE sequenceIdentifier = ?");
st.setString(1, sequenceIdentifier);
SQLException retried = null;
for (;;) {
ResultSet rs = st.executeQuery();
if (!rs.next()) {
if (retried != null)
throw retried;
PreparedStatement ins = con.prepareStatement("INSERT INTO SequenceValue (sequenceIdentifier, sequenceValue) VALUES (?, ?)");
ins.setString(1, sequenceIdentifier);
ins.setLong(2, 0);
try {
ins.executeUpdate();
}
catch (SQLException ex) {
// store the exception and rethrow if next query retry fails
retried = ex;
}
}
else {
long value = rs.getLong(1);
PreparedStatement upd = con.prepareStatement("UPDATE SequenceValue SET sequenceValue = sequenceValue+1 WHERE sequenceIdentifier = ? AND sequenceValue = ?");
upd.setString(1, sequenceIdentifier);
upd.setLong(2, value+1);
if (upd.executeUpdate() == 1)
return value+1;
}
}
}
finally {
con.close();
}
Briefly: The code avoid transactions completely. At the beginning it tries to retrieve the sequence value according to identifier. In case it's not found, it attempts to create it and retries retrieving again. It doesn't fail in case the value was created in the meantime.
If the value is found, it tries to increment it using atomic update on the row. If it succeeds then it returns the incremented value, if not it retries again.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to call a method from servlet. I have below class:
public class course {
public ResultSet course_in_dept(String dept_name) {
ResultSet rs = null;
try {
String Query = "select course_id , title from course where dept_name=?";
PreparedStatement pst = Database.dbConnect().prepareStatement(Query);
pst.setString(1, dept_name);
rs = pst.executeQuery();
return rs;
} catch (Exception e) {
Database.error = 1;
return null;
}
}
}
And now I want to call course_in_dept method from this class in doPost method of my servlet. Now how I can handle it?
Try create instance and call it like:
course courseResult = new course();
ResultSet resultSet = courseResult.course_in_dept("Engineering");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
so I'm trying to connect to a database using java.. there's a problem at a function I wrote getOutSymptoms.
Here's the code
package database_console;
import java.sql.*;
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users", "root", "admin");
st = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getOutSymptoms(int userID) throws SQLException{
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
rs = st.executeQuery(query);
int out_symptoms_value = rs.getInt("out_symptoms");
st.close();
return out_symptoms_value;
}
the error is at the getOutSymptoms function, at the line:
int out_symptoms_value = rs.getInt("out_symptoms");
why is that? and how can I fix it?
thank u so much.
You need to iterate through your result set in order to get the returned rows. When you first get your new ResultSet, it's not pointing to any particular row (its pointer is set to a row before first) and you need to call rs.next() method at least once to get to the actual results.
If you know there can be only one result you can do something like this:
if (rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do other stuff
} else {
//query returned no results
}
If you expect to have more than one row returned, then you can do this:
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do the rest of processing
}
TLDR: You need to call rs.next() at least once to get to the actual results.
In order to start using a ResultSet, you must call the next() method. Although you haven't stated the exact error, you will definitely run into this problem unless it is added before you call getInt().
http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
you need to iterate through the resultSet object using rs.next() to get the value. resultSet doesn't point to the actual row but when you call rs.next() it points to first result.
while(rs.next(){
int d = rs.getInt(" ");
}
rs.next() returns a boolean value , incase nothing is returned the loop will not execute & you will not get an Exception at runtime.
You have already passed the database name in connection string so change this
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
to
String query = "SELECT out_symptoms FROM tableName WHERE id =" + userID;
Then just iterate over the obtained ResultSet like this
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
}
Moreover its good to use PreparedStatement instead of Statement which cna prevent you from sql injection