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");
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 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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I made a Java Forum and im trying to search my sql table, when i click the button to finally search it (the name of the person) it comes up with a "Invalid Operation at Current Cursor Position" error.
Here'e my code for the search button. Please help me figure this out.
private void firstSearchActionPerformed(java.awt.event.ActionEvent evt) {
try{
String fname = searchText.getText();
Connection connect = DriverManager.getConnection("jdbc:derby://localhost:1527/Employees",
"users", "admin");
PreparedStatement pState = connect.prepareStatement("select * from WORKERS where First_Name = ?");
pState.setString(1,fname);
ResultSet rSet;
rSet = pState.executeQuery();
if(rs.next()){
int id_col = rSet.getInt("Employee_ID");
String id = Integer.toString(id_col);
String first = rSet.getString("First_Name");
String last = rSet.getString("Last_Name");
String job = rSet.getString("Title");
String hireDate = rSet.getString("Hire_Date");
textID.setText(id);
textFirstName.setText(first);
textLastName.setText(last);
textTitle.setText(job);
textHireDate.setText(hireDate);
}else{
JOptionPane.showMessageDialog(null, "Not in Database");
}
}catch(SQLException err){
JOptionPane.showConfirmDialog(employees.this, err.getMessage());
}
}
ResultSet rSet;
rSet = pState.executeQuery();
instead of
if(rs.next()){
use
if(rSet.next()){
Here resultset object is rSet not rs
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