Why does alphanumeric id search not working properly in Java Swing? - java

I have a search field in Java swing to search Books. I have UI having text field jtxtSearch to enter values and one Field JCombobox for categories. Though it's working for all other fields but not for id search. However when having a pretext in the book id (eg: sp001) its working and populating on jtable. My code is as below.
public List<Book> searchBookBy(String search, String field){
List<Book> results = new ArrayList<Book>();
String sql = null;
Statement stmt = null;
ResultSet rs = null;
if(field.equalsIgnoreCase("id")){
if(search.length() == 0) search = "0";
sql = "SELECT * FROM books WHERE id = " + search;
}else{
sql = "SELECT * FROM books WHERE " + field + " LIKE '%" + search + "%'";
}
After this is my try and catch to set variable id etc. The DB is MySQL.

Related

SQL ResultSet is empty despite having a row returned in tests

I am building a simple program for a library database system in Java where patrons can borrow and return books. The database has 4 tables: Book, Author, Patrons, and AuthorIds. I'm using the SQL statement below to retrieve 1 row of data that includes everything plus a column that counts how many books the patron has already borrowed. The problem is that the program never goes into the while(res.next()) loop and I think it's because the result set is empty. The test print doesn't get printed and membID doesn't get changed to the MemberID of the patron.
But when I try that same SQL statement on db browser on the same database it returns 1 row as expected with the BooksBorrowed column. All of my other ResultSet while loops have worked and returned rows with other SQL statements, it's just this one that doesn't and I don't know why.
public void borrowBooks(String fName, String lName, Scanner input) throws SQLException {
//first find out how many books the user has already borrowed
int booksBorrowed = 0;
int membID = 1; //this will be used for later
sql = "select *, Count(MemberID) AS BooksBorrowed\r\n" +
"FROM Book\r\n" +
" JOIN AuthorIds USING (BookID)\r\n" +
" JOIN Author USING (AuthorID)\r\n" +
" JOIN Patron USING (MemberID)\r\n" +
"WHERE PatronFirstName LIKE ? AND PatronLastName LIKE ?\r\n" +
"GROUP BY MemberID\r\n" +
"ORDER BY BookID ASC";
PreparedStatement stmt = connection.prepareStatement( sql );
stmt.setString(1, fName);
stmt.setString(2, lName);
ResultSet res = stmt.executeQuery();
while(res.next()) {
booksBorrowed = res.getInt("BooksBorrowed");
System.out.println(res.getInt("MemberID"));
System.out.println("Test");
membID = res.getInt("MemberID");
}
if(booksBorrowed >= 2) {
System.out.println("You have already borrowed the maximum amount of 2 books. Return books to borrow more");
}
I figured it out and it was that I should have gotten the memberID in a separate query because I was trying to change it to the corresponding patron in the same query as I was trying to get the number of books borrowed. The problem was that if the patron didn't have any books borrowed, then the result set would be empty and the memberID wouldn't change from what it was temporarily initialized as. This memberID was later inserted into the table for when a book was borrowed so it would be the temporary stand in each time and not the actual memberID of the patron, so the patron would have no books under their name as borrowed.

How can I pass a string value to another jsp page using session.setAttribute ("", table) why it's not executing? "select * from " + table + "";?

Why mysql query string query ="select * from " + table + "";` is not working the table name is coming from another jsp page.
And why session. setAttribute ("", "table");` is not working to import string from jsp to jsp?
I have two jsp file in my code one is for selection of table for username and password to get login the file name is statement.jsp and other file statement is for showing data in a table that is selected in statement3.jsp. I want to use table string in another jsp page to show that table.
error
String query ="select * from " + table + ""; //for selection of table
session.setAttribute("", "table"); //To pass String table from statement.jsp to statement3.jsp to show table.
statement3.jsp
<%
ResultSet rs = null;
session.setAttribute("", "table");
String query ="select * from " + table + "";
rs=st.executeQuery(query);
%>
statement.jsp
<%
ResultSet rs = null;
String name=request.getParameter("username");
String abc=request.getParameter("password");
String gender = request.getParameter("gender");
if (gender != null) {
String table = gender.equals("teacher") ? "teacher2" : "student";
out.println(table);
String query ="select * from " + table + " where username='"+name+"' AND password='"+abc+"'";
rs=st.executeQuery(query);
out.println(rs);
if(rs.next())
{
response.sendRedirect("statement3.jsp");
}
else
{
response.sendRedirect("index.jsp");
}}
%>
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:93)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:435)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:298)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:277)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:265)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:302)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
If you want to put the value of the variable table in the session you can do this:
String table = "whateverTableNameYouWant";
session.setAttribute("mySessionVariableName", table);
If you want to read that value in another jsp, you can do this:
String table = (String)session.getAttribute("mySessionVariableName");

Usage of Multiple Queries to get data from different tables

I am new to DATABASE and MYSQL so don't have much experience or knowledge with handling queries
I have two tables students and login in MYSQL database, they both have 1:1 relation, Primary key of student is a foreign key in login.
So login table has both Student_ID(FK) and Password
I want to run a query in a JAVA program that will check the id and password entered by the user in login table and then return the matching student object data from student table
So far this is what I am doing for login the user put in username and password
public Student validate_Student(String s, String t)
{
int w = Integer.parseInt(s);
int q = 0;
String iD = "";
Student obj = new Student();
String query = "SELECT * FROM login WHERE Student_ID = " + w + " and Password= " + t;
try
{
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
iD = rs.getString("Student_ID"); //matching record
}
int i = Integer.parseInt(iD); // check the previously searched matching record in student table
String query1 = "SELECT * FROM student WHERE ID = " + i;
ResultSet rs1 = stmt.executeQuery(query);
while (rs1.next()) {
obj.setID(rs1.getString("ID"));
obj.setName(rs1.getString("NAME"));
obj.setAddress(rs1.getString("ADDRESS"));
obj.setPhone(rs1.getString("PHONE_NO"));
obj.setEmail(rs1.getString("EMAIL"));
obj.setDOB(rs1.getString("DOB"));
obj.setDegree(rs1.getString("DEGREE"));
}
}
catch(SQLException e)
{
System.out.println("Problem in Query");
e.printStackTrace();
}
return obj;
}
I am not quite sure how to use UNIONS in the query
Below query will return student details whose login credentials match.
SELECT s.* FROM student s JOIN login l on s.id = l.Student_ID WHERE l.Student_ID = " + w + " and l.Password= '" + t + "'";
Join student table to login table using one to one relation s.id = l.Student_ID where s is the alias for student table and l for login table.
to return only student details use s.* in select statement.

Multiple keyword search with Java & MySQL

I'm trying to write a Java code snippet to return the keywords contained in the description of a specific entity & SELECT only those records that contain both keywords.
The following code works, however it returns entities whose body contains only one or the other of the words. I need it to return only those records that contain both keywords, not just one of them.
try {
String search = txt_search.getText();
search = search.trim();
search = search.replace (' ','|');
String sql = "SELECT * FROM catagory WHERE keywords REGEXP '" + search + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()){
String add1 = rs.getString("CatagoryId");
txt_catagoryid.setText(add1);
String add2 = rs.getString("CatagoryName");
txt_catagoryName.setText(add2);
String add3 = rs.getString("keywords");
txt_keywords.setText(add3);
rs = stmt.executeQuery(sql);
catagoryTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
...
}

How to Run Query on Long number

Hello everyone i am trying to run a simple query on a long number i have tried but still returns me id type is long integer. I am getting all the data a jTable and the 1st column is of id when i ever click on the row it always gives me this exception and i have got the correct value from table when printed in console
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
My code is :
int row = recordsTable.getSelectedRow();
String tableValue = (recordsTable.getModel().getValueAt(row, 0).toString());
String qry = "Select * from records where id ='" + Long.parseLong(tableValue) + "'";
try {
db.setStmt((Statement) db.getCon().createStatement());
ResultSet rs = ((java.sql.Statement) db.getStmt()).executeQuery(qry);
if (rs.next()) {
id=rs.getLong("id");
idTextField.setText(Long.toString(id));
customerCode = rs.getString("customer_code");
custCodeTextField.setText(customerCode);
firstName = rs.getString("first_name");
firstTextField.setText(firstName);
lastName = rs.getString("last_name");
lastTextField.setText(lastName);
customerContact = rs.getString("customer_mobile");
custMobTextField.setText(customerContact);
customerAddress = rs.getString("customer_address");
custAddressTextField.setText(customerAddress);
fillComboBox();
area=rs.getString("area");
areaComboBox.setSelectedItem(area);
payment_this_month = rs.getInt("payment");
paymentTextField.setText(Integer.toString(payment_this_month));
duePayment = rs.getInt("balance");
balTextField.setText(Integer.toString(duePayment));
java.util.Date dateSet = rs.getDate("bill_issued_on");
billTextField.setText(dateSet.toString());
connectionStatus = rs.getString("connection_status");
jComboBox2.setSelectedItem(connectionStatus);
Remove the single quotes around
'" + Long.parseLong(tableValue) + "'"

Categories

Resources