returning multiple values in web service - java

I am designing a web-service using java and eclipse which returns the user details who are marked as customer in the database
I was successfully able to return details for a single user (as there was only one entry in the dB) with the following code:
public class GetData {
public LoginDetails getDetails(){
Connection conn;
Statement stmt;
ResultSet rs;
try {
LoginDetails lds=new LoginDetails();
Class.forName(driver);
conn=DriverManager.getConnection(url,username,password);
stmt=conn.createStatement();
String sql="select * from login where usertype='customer'";
rs=stmt.executeQuery(sql);
while(rs.next()){
lds.setUsername(rs.getString(1));
lds.setPassword(rs.getString(2));
lds.setUsertype(rs.getString(3));
lds.setActive(rs.getString(4));
}
return lds;
}
catch(ClassNotFoundException c){
c.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
What should I do if there are multiple values in dB matching the criteria and I want to display them all. Please advice.

Change your method signature to public LoginDetails[] getDetails()
And extend your while loop as follows:
Collection<LoginDetails> details = new ArrayList<LoginDetails>();
while(rs.next()){
LoginDetails lds=new LoginDetails();
lds.setUsername(rs.getString(1));
lds.setPassword(rs.getString(2));
lds.setUsertype(rs.getString(3));
lds.setActive(rs.getString(4));
details.add(lds);
}
return details.toArray(new LoginDetails[0]);

Return an collection type suggestively java.util.List , preferably ArrayList from the method.

Related

PreparedStatement won't send data over to database

I'm unsure as to why my program won't actually send the data supplied over to the table in my database table. I'm using a JavaFX application table to select a client from the table when selected and when signed in, the method sends the info to the DBconnect class to perform the operation.
Method to send the data to the DBconnect class:
public void signIn() throws SQLException {
BloomClient person = clientList.getSelectionModel().getSelectedItem();
dBconnect.sendToRoster(person.getFirstName(),person.getLastName());
}
Method to perform PreparedStatement:
public void sendToRoster(String fName, String lName) throws SQLException {
PreparedStatement st = c.prepareStatement("INSERT INTO sign_in_roster VALUES(?,?,?,?);");
c.setAutoCommit(false);
try {
st.setString(1,fName);
st.setString(2,lName);
st.setString(3, systemDate());
st.setString(4, systemTime());
c.commit();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
You've set all the bind variables, but you've forgot to execute the statement:
st.setString(1,fName);
st.setString(2,lName);
st.setString(3, systemDate());
st.setString(4, systemTime());
st.executeUpdate(); // Here
c.commit();

Fetching data in JSP on PreparedStatement

When Try to fetching Data in database result it come zero row but when try to copy and past query on mysql has return specific number of rows needed.
Connection to mysql server
private Connection connection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/olesdb", "root", "");
} catch (Exception e) {
//System.out.println("Connection error");
}
return con;
}
**
My function for fetching data
**
public List<AcademicYearCourses> getStudentCourse(int studentID, int academicYear,int semester) throws SQLException{
List<AcademicYearCourses> list = new ArrayList<>();
PreparedStatement sta = connection().prepareStatement("SELECT courseCode,courseName FROM courses co,studentprograms stpro,academicyearcourse acco WHERE stpro.studentID=? AND acco.academicYearID=? AND acco.semesterID=? AND stpro.programID= acco.programID AND stpro.studyYear=acco.studyYear AND acco.courseID=co.courseID");
sta.setInt(1, studentID);
sta.setInt(2, academicYear);
sta.setInt(3, semester);
ResultSet res = sta.executeQuery();
while(res.next()){
AcademicYearCourses acco = new AcademicYearCourses();
acco.setAcdemicYearCourseID(rs.getInt("acdemicYearCourseID"));
acco.setCourseName(rs.getString("courseName"));
acco.setCourseCode(rs.getString("courseCode"));
list.add(acco);
}
return list;
}
So I need help to solve this issue it very important in my project and Cant continue without this data
Your are doing rs.getInt("acdemicYearCourseID") but column acdemicYearCourseID is not in your SELECT columns list.
Also try changing getInt("..."), getString("...") to getInt(1), getString(2)

How do I call data from a table in a database into a java class in netbeans?

first time posting so sorry if my question is slightly strange.
So I have a project in school that requires us to create java classes using netbeans that open up a window with three options, check stock, purchase item and update stock.
We had a class called stockdata that held the details of 5 different items for us to use in our three classes to check, purchase and update items. The latest stage of our coursework requires us to create a derby database and enter the items into a table.
I have done this with no issues but I am having a problem getting the items from the table back into my classes to use. We were given the following code but I can't get it to work, even using the commented hints.
package stock;
// Skeleton version of StockData.java that links to a database.
// NOTE: You should not have to make any changes to the other
// Java GUI classes for this to work, if you complete it correctly.
// Indeed these classes shouldn't even need to be recompiled
import java.sql.*; // DB handling package
import java.io.*;
import org.apache.derby.drda.NetworkServerControl;
public class StockData {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to an Access database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("UserDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "use", "use");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
} catch (SQLException sqle) {
System.out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
// You could make methods getName, getPrice and getQuantity simpler by using an auxiliary
// private String method getField(String key, int fieldNo) to return the appropriate field as a String
public static String getName(String key) {
try {
// Need single quote marks ' around the key field in SQL. This is easy to get wrong!
// For instance if key was "11" the SELECT statement would be:
// SELECT * FROM Stock WHERE stockKey = '11'
ResultSet res = stmt.executeQuery("SELECT * FROM Stock WHERE stockKey = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
public static double getPrice(String key) {
// Similar to getName. If no result, return -1.0
return 0;
}
public static int getQuantity(String key) {
// Similar to getName. If no result, return -1
return 0;
}
// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
// SQL UPDATE statement required. For instance if extra is 5 and stockKey is "11" then updateStr is
// UPDATE Stock SET stockQuantity = stockQuantity + 5 WHERE stockKey = '11'
String updateStr = "UPDATE Stock SET stockQuantity = stockQuantity + " + extra + " WHERE stockKey = '" + key + "'";
System.out.println(updateStr);
try {
stmt.executeUpdate(updateStr);
} catch (SQLException e) {
System.out.println(e);
}
}
// close the database
public static void close() {
try {
connection.close();
} catch (SQLException e) {
// this shouldn't happen
System.out.println(e);
}
}
}
Sorry if this seems a stupid question but I am fairly new to Java and was making good progress until this roadblock.
Thanks in advance!
Alex
Searching for "java sql" on Google delivers this link: https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
From a connection you can create a statement (you can find this in the link and in your code) , then fetch a result set and loop over that with rs.next(). That should get your started.
Of course you have to make sure that the driver and database are there/running, just saying...
Here netbeans has nothing to do with database. This is a Java-based integrated development environment(IDE) that will help you to reduce syntactic error.
public void dataAccess(){
try {
String connectionUrl = "suitable connection url as per your database";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("JDBC driver name as per your database");
con = DriverManager.getConnection(connectionUrl, userName, password);
String SQL = "SQL query as per your criteria";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
// look into ResultSet api and use method as per your requirement
}
rs.close();
}
catch (Exception e) {
//log error message ;
}
}

What is wrong with my login validation code? I;m using Java Swing & MySQL

I am a beginner and I just began writing my first real GUI project. I intend to create a simple school management system and I just finished creating the signup and login screens.
The signup page works fine, it adds user details to the mySQL database seamlessly. The problem is I can't get the login page to validate the details correctly. Each time I enter a correct password/username it displays the failure message. Which is what it should do when the details are wrong.
I have 2 classes, the main class holds the login page code, and the second class deals with the connection to the DB and also defines the methods for Login which are then called in the main class.
Here's my code. Please help out. Thank you.
`
//VALIDATE LOGIN
public Boolean checkLogin (String username, String password) {
//SQL STATEMENT
String sql = "SELECT * FROM `school_management_system`.`login_details` WHERE `username`=? and `password`=?";
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/school_management_system","root","mathenge24");
pst = con.prepareStatement(sql);
System.out.println("Conected successfully");
//PREPARED STATEMENT
pst.setString(1, username);
pst.setString(2, password);
//EXECUTE PREPARED STATEMENT
rs = pst.executeQuery();
if(rs.next()) {
//Returns true if the query finds any corresponding data
return true;
} else {
return false;
}
} catch(SQLException exc) {
exc.printStackTrace();
return false;
}
}
`
Here is the action perfomed code for the login button:
private void loginbtnActionPerformed(java.awt.event.ActionEvent evt) {
//String temp_pwd = passwordtxt.getText();
//Call checklogin() to authenticate details
DBconnect db = new DBconnect();
if(db.checkLogin(usernametxt.getName(), passwordtxt.getText())) {
//POP UP MESSAGE
JOptionPane.showMessageDialog(null, "You have logged in succesfully", "Success", JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
dispose();
}
else {
//popup box
JOptionPane.showMessageDialog(null, "Login failed!", "Failed!", JOptionPane.ERROR_MESSAGE);
}
In loginbtnActionPerformed you call tje verification with
(usernametxt.getName(
You would'nt want the component's name, do you?
usernametext.getText ()
Will work better :-)
if you don't have any exceptions i guess your result set has the size of zero...
validate simply by using this code:
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/school_management_system","root","mathenge24");
pst = con.prepareStatement(sql);
System.out.println("Conected successfully");
//PREPARED STATEMENT
pst.setString(1, username);
pst.setString(2, password);
//EXECUTE PREPARED STATEMENT
rs = pst.executeQuery();
return true;
} catch(SQLException exc) {
return false;
}

Add ComboBoxItem from MS Access Database

I am trying to add ComboxItem from database. I have write the code given below. When I run the program it give a error message.
Message is
java.sql.SQLException:Driver does not support this function
someone please help me.
here is my code
public class DepositFirstForm extends javax.swing.JFrame {
Connection conn=null;
ResultSet rst=null;
PreparedStatement pst=null;
private void ItemComb(){
private void ItemComb(){
String sql="SELECT * FROM account_type";
try
{
pst=conn.prepareStatement(sql);
rst=pst.executeQuery(sql);
while(rst.next()){
String actype=rst.getString("account_type");
dfcmb1.addItem(actype);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
private void formWindowOpened(java.awt.event.WindowEventevt) {
// TODO add your handling code here:
conn=Connect.connectDB();
ItemComb();
}
}
my table name is account_type
serial_no account_type
1 regular
2 premium
3 golden
Try removing the (sql) parameter from you call to pst.executeQuery:
rst = pst.executeQuery();
Since your PreparedStatement is already created using the SQL.
I trust you are declaring conn, pst and rst somewhere.

Categories