control never seems to go in the if block - java

I find that the control never seems to go in if block that starts from "if(sqlquery.equals("1"))" when it actually returns to be true. What could be the reason to it and how should ! modify it ?My program code is :
//package searchbook;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
public class SearchBook extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
HttpSession session = request.getSession(true);
List booklist=new ArrayList();
Connection con = null;
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "";
String pass = "";
String category="";
category=request.getParameter("input");
String sqlquery="select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%"+category+"%' ";
try
{
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try{
Statement st = con.createStatement();
System.out.println("Connection created 1");
ResultSet rs = st.executeQuery(sqlquery);
System.out.println("Result retreived 1");
//System.out.println('"sqlquery"');
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed! "+ s);
}
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("************");
//String sqlq="";
if(sqlquery.equals("1"))
{
String sqlq="select Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name, Metrics.Metric_Name "
+ "FROM Section , Report , Contact,Metrics "
+ "WHERE Report.Contact_ID=Contact.Contact_ID and Report.Section_ID=Section.Section_ID "
+ "and Report.Report_ID IN (SELECT Metrics.Report_ID FROM Metrics WHERE Metrics.Metric_Name = Report.Report_ID') and Metrics.Metric_Segment = 'M' ";
System.out.println("2nd query executed too !");
try
{
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try
{
Statement st = con.createStatement();
System.out.println("Connection created");
ResultSet rs = st.executeQuery(sqlq);
System.out.println("Result retreived ");
while (rs.next())
{
List<String> book=new ArrayList<String>();
String Name=rs.getString("Section_Name");
String reportName=rs.getString("Report_Name");
String link=rs.getString("Link");
String contactName=rs.getString("Contact_Name");
String metricName=rs.getString("Metric_Name");
//String reportId=rs.getString("Report_ID");
/*String ind_id=rs.getString("index_name");
String ind_name=rs.getString("link_id");*/
book.add(Name);
book.add(reportName);
book.add(link);
book.add(contactName);
book.add(metricName);
//book.add(reportId);
/*book.add(ind_id);
book.add(ind_name);*/
booklist.add(book);
}
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed! "+ s);
}
}
catch (Exception e) {
e.printStackTrace();
}}
System.out.println("And it came here lastly !");
request.setAttribute("booklist",booklist);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/searchbook.jsp");
dispatcher.forward(request, response);
}
}

You're setting your variable
String sqlquery="select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%"+category+"%' ";
and then comparing it to 1:
if(sqlquery.equals("1"))`
which will never be true
add a String sqlResult = null; right after your sqlquery declaration
and add a sqlResult = rs.getString(1) right after your
rs = st.executeQuery(sqlquery);
then compare with sqlResult instead of sqlQuery

I suspected that you are trying to compare "string" with "int" :
if(sqlquery.equals("1"))
So it will obviously not go inside the statement.
Instead you can try this
if(sqlquery != null)

Of course it won't. sqlquery is a string containing the SQL-code ("SELECT ...").

Your string sqlquery contains a select statement so will never be equal to "1".
You need to check the result of your query, not the query string itself.
To do that, you're going to need to define rs (and the Statement as well, I believe) before the try block (so it stays in scope after that block), then evaluate it to see if it returned the data you desired.
How you do that depends on whether that "1" is meant to represent the number of rows returned or the data itself returned (from Index1.link_id).

Related

jdbc oracle 11g PreparedStatement not producing results

I am trying fetch data based on a condition on committee column using jdbc.Using Statement it produces the desired result but using PreparedStatement it does not.I cannot figure out what has gone wrong.Kindly help.Here is both the programs one using Statement and the other one using PreparedStatement and my table structure as well
import java.sql.*;
class SelectPrepared {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = 'GENERAL'";
Statement stmt = con.createStatement();
// stmt.setString(1,"GENERAL");//1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery(sql);
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.sql.*;
class SelectPreparedOne {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String s = "GENERAL";
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s);// 1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery();
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Table structure
USERNAME VARCHAR2(40)
PASSWORD VARCHAR2(40)
ROLE VARCHAR2(40)
NAME VARCHAR2(40)
DESIGNATION VARCHAR2(40)
DEPARTMENT VARCHAR2(40)
EMAILID VARCHAR2(40)
COMMITTEE CHAR(15)
TL/DR: don't use char use varchar2
CHAR(15) gets blank padded to 15 characters, so the column contains the value 'GENERAL ' and that's not equal to the supplied value of 'GENERAL'
The correct fix is to change the column to VARCHAR2(15)
An intermediate ugly workaround (until you fix the column definition) is to use trim:
where trim(committee) = ?;

How to add more `?` automatically in java in accordance with whatever amount of columns will be placed in the interface

I'm trying to create an api so I can use it to whatever project I need to create. I'm still new to java so I'm sorry in advance for the wrong codes. Anyways, I've got here this code that has the CRUD statements (except for Read/Retrieve).
import java.sql.*;
public class KitApiNew {
public static void main(String[] args) throws SQLException {
Connection dbConnection = null;
PreparedStatement PSInsert = null;
PreparedStatement PSUpdate = null;
PreparedStatement PSDelete = null;
PreparedStatement PSStatement = null;
String DBTable = "fruits";
String DBColumnSet = "fruit";
String DBID = "23";
String DBColumnSingle = "fruit";
String DBChoice ="insert";
String DBCS = "";
String insertTable = "INSERT INTO " + DBTable + "(" +DBColumnSet+ ")" + "VALUES" + "(?)";
String updateTable = "UPDATE " + DBTable + " SET " + DBColumnSingle + " = ?" + " WHERE id = ?";
String deleteTable = "DELETE FROM " + DBTable + " WHERE id = ?";
String statementTable = "INSERT INTO fruits(fruit) VALUES('grapes')";
try{
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
if(DBChoice.equals("insert")){
//for insert
PSInsert = dbConnection.prepareStatement(insertTable);
PSInsert.setString(1, "Orange");
PSInsert.executeUpdate();
dbConnection.commit();
}
if(DBChoice.equals("update")){
//for update
PSUpdate = dbConnection.prepareStatement(updateTable);
PSUpdate.setString(1, "Apple");
PSUpdate.setString(2, DBID);
PSUpdate.executeUpdate();
dbConnection.commit();
}
if(DBChoice.equals("delete")){
//for delete
PSDelete = dbConnection.prepareStatement(deleteTable);
PSDelete.setString(1, DBID);
PSDelete.executeUpdate();
dbConnection.commit();
}
if(DBChoice.equals("statement")){
//for statement
PSStatement = dbConnection.prepareStatement(statementTable);
PSStatement.executeUpdate();
dbConnection.commit();
}
System.out.println("Success!");
}catch(SQLException e){
System.out.println("Error occured " + e.toString());
dbConnection.rollback();
}
finally{
if(PSInsert !=null){
PSInsert.close();
}
if(PSUpdate != null){
PSUpdate.close();
}
if(dbConnection != null){
dbConnection.close();
}
}
}
private static Connection getDBConnection(){
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("Error 1 : " + e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bongbong","root","");
}catch(SQLException e){
System.out.println("Error 2 : " + e.getMessage());
}
return con;
}
}
Oh by the way,
The values of the variables are currently temporary. I'll be changing them later to whatever they're going to be catching. I'm referring to these:
String DBTable = "fruits";
String DBColumnSet = "fruit";
String DBID = "23";
String DBColumnSingle = "fruit";
String DBChoice ="insert";
String DBCS = "";
and this
String statementTable = "INSERT INTO fruits(fruit) VALUES('grapes')";
Problem
What I really need help from is with the ? thing from the first code I posted after the VALUES word inside the String insertTable. I want it so that when I place a column amount in my interface then it'll add more ? in accordance with what was inputted (I also want it to add another PSInsert.setString(n, "value") with n+1 in accordance with the column amount inputted if it's possible). Can anyone tell me how to? I'm really new to java and I'm still a student studying at his best.
I want it to add those ? thing because what if I add more columns or if I use another table with more columns other than my fruits table. (I want it so that whatever I'm going to place in DBColumnSet --with columns separated by comma --will also relate to how many ? are going to be placed).
Oh by the way, it's a general api so I can't provide an interface.

Delete from SQLite Database

I have an SQLite database linked up to my Java project within Eclipse. I'm able to delete entries from the database when I give a hardcoded, specified ID such as '3'. I'm trying to alter the code in order to enable the user the manually pass any number and have it delete that entry.
public static String deleteRecords(String NumberDelete){
Connection dbConnection = null;
Statement statement = null;
try{
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
statement = dbConnection.createStatement();
String sql = "DELETE from employees where ID='NumberDelete';";
statement.executeUpdate(sql);
dbConnection.commit();
statement.close();
dbConnection.close();
} catch(Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return NumberDelete;
}
You need to use PreparedStatement to pass the parameters to query and execute it, the method will look like this:
public static String deleteRecords(String NumberDelete) {
Connection dbConnection = null;
PreparedStatement statement = null;
String sql = "DELETE from employees where ID= ? ;";
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
statement = dbConnection.prepareStatement(sql);
statement.setString(1, NumberDelete);
statement.executeUpdate(sql);
dbConnection.commit();
statement.close();
dbConnection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return NumberDelete;
}
This will set the number in the query and execute it. If the number is of type int then you need to use setInt to set the value. Here is the javadoc for PreparedStatement.
For user input, you might want to check out the Scanner class: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Once you get an integer from the user, parse it, and store it in a variable, you can simply use String concatenation:
String sql = "DELETE from employees where ID='" + userInput + "';";

class to connect java program to database(which accepts parameters)

I'm trying to write a class that will accept two strings and an int (username and password and score) from a quizgame, which eventually will come from a GUI, at the minute I'm just passing them through from the main, and pass them into a database to be inserted.
I have the JConnector jar file added and am working in Eclipse.
Here is my code
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
//public
class DbConnect {
private java.sql.Connection con;
private java.sql.Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (n,p,x)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.executeUpdate();
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
The error I get is
Unknown column 'n' in 'field list'
I can directly put a string in like 'john' but that is no use to me in this situation.
Instead of INSERT INTO nostalgic values (n,p,x) you should have
INSERT INTO nostalgic values (?,?,?) and then:
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setString(3,x);
statement3.executeUpdate();
in
String query1 = "INSERT INTO nostalgic values (n,p,x)";
n,p,x are not being replaced with the values, they are just being considered as some char that's why you get this error
Edit : before statement3.executeUpdate();
String query1 = "INSERT INTO nostalgic values (?,?,?)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setInt(3,x);
Update: you may wonder why Unknown column 'n' in 'field list'?
Because as insert query in sql can have this structure
INSERT INTO table (col1,col2,...) values (`val1`,`val2`,....)
but then values need to be inside `` if hard coded so if there is no `` sign they are considered as column name.
Mick,
the problem is that you don't pass actual parameters to your query when doing statement3.executeUpdate();. Check this link to see how to do it: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
You cannot do it like that try this:
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/nostalgic","root","usbw") {
PreparedStatement pr = null;
String query = "INSERT INTO nostalgic VALUES ((?), (?), (?))";
pr = con.prepareStatement(query);
pr.setString(1, n);
pr.setString(2, p);
pr.setString(3, x);
int status = pr.executeUpdate();
}catch (ClassNotFoundException | SQLException e) {
System.out.println(e.getMessage());
}
There are some mistakes in your code...
Correct imports
Insert statement
Your code will be like that:
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.jdbc.Statement;
// you imported sql innecessary statements...
//public
class DbConnect {
// dont need complete path, you already imported it
private Connection con;
private Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (?,?,?)";
// no need to define vars here,
// just number of places to be inserted here ----^
PreparedStatement statement = con.prepareStatement(query1);
// prepare statement
statement = con.prepareStatement(query);
// insert the variables in places you prepared before
// and matching the types you need!!!
statement.setString(1,n);
statement.setString(2,p);
statement.setInt(3,x);
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}

SQL query in eclipse

I have my connection class like this:
public class Codb {
public static Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" +
"localhost:3306/bd1";
String user = "root";
String passwd = "root";
Connection conn = (Connection) DriverManager.getConnection(url, user, passwd);
//Création d'un objet Statement
Statement state = conn.createStatement();
//L'objet ResultSet contient le résultat de la requête SQL
ResultSet result = state.executeQuery("SELECT * FROM consomateur");
//On récupère les MetaData
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
System.out.println("\n**********************************");
//On affiche le nom des colonnes
for (int i = 1; i <= resultMeta.getColumnCount(); i++)
System.out.print("\t" + resultMeta.getColumnName(i).toUpperCase() + "\t *");
System.out.println("\n**********************************");
while (result.next()) {
for (int i = 1; i <= resultMeta.getColumnCount(); i++)
System.out.print("\t" + result.getObject(i).toString() + "\t |");
System.out.println("\n---------------------------------");
}
result.close();
/*state.close();*/
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The user enter the id and I want to know if the id is in the database, I created a servletin which I declared this:
static Statement St;
public ResultSet rs;
and then I have this method that verifies if the id exists or not, but it doesn't work for me.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String req = "select id from db1.consomateur ";
try {
St = (Statement) Codb.Con.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
rs = (ResultSet) St.executeQuery(req);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet id = rs;
String un = request.getParameter("id");
String msg = " ";
if (un.equals(id)) {
msg = "Hello " + un + " your login is sucess";
} else {
msg = "Hello " + un + " your login is unsucess";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font siez='6' color=red>" + msg + "</font>");
}
Two ways to improve your code.
1. One simple thing, just iterate over the results in result set and check for the id that you are querying. What your are doing is, you are comparing id (referred as un your code) with result set (referred as id in your code) which is wrong. Result Set is a complex data structure which contains the sql query result data and meta data about it. Your comparison of ResultSet id with query parameter id is wrong. So one way is to iterate over the result set and compare the value of id of every row with query parameter id value and break the loop when match is found. Example: Taking over from your code
ResultSet id = rs;
String un = request.getParameter("id");
boolean flag = false;
while (id.next()) {
String i = id.getString("id");
if(un.equals(i)){
flag = true;
break;
}
}
if(flag){
msg="Hello "+ un + " your login is sucess";
}
else{
msg="Hello "+un + " your login is unsucess";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font size='6' color=red>"+ msg+ "</font>");
So what I did is, i iterate over the result set and for each value of result set, I compared it with query parameter that u sent. If it is matched, I got a hit and I set my flag to true which mean found and I break my loop as there is no point in looking ahead. Otherwise, my loop will eventually end when all the result set entries are exhauted and nothing matches. Therefore, my flag will remain false and later I used that flag variable to set corresponding message for the case.
2. The first way is way too time consuming as the number of comparisons happening is far too much if your database contains lot of rows. On the other hand, if we modify our query a bit and use the sql where clause we can let databse handle the matching and we will enjoy the ease of programming at our end. I hope the id field in db1.consomateur is primary key, then we can use this peice of code to make our life easy.
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String id = request.getParameter("id");
String req = "select id from db1.consomateur where id = "+id;
boolean flag = false;
try{
Connection c = Codb.connect();
Statement st = (Statement) c.createStatement();
ResultSet rs =(ResultSet)st.executeQuery(req);
if(rs != null){
if(rs.next())
flag = true;
}
}
if(flag){
msg="Hello "+ un + " your login is sucess";
}
else{
msg="Hello "+un + " your login is unsucess";
}
catch(Exception e){
msg = e.getMessage();
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font size='6' color=red>"+ msg+ "</font>");
}
So, if query get executed and we have result set not equal to null i.e. we have some data, we can check whether rs contains any rows. Since, id is a primary key, rs will contain only one row and rs.next will point to that row. Therefore, it will be our match and we have set our flag there. Otherwise flag will be false. In this case database itself take care of matching the ids and returning only the matching row to us. So, it will be faster as database create index over primary keys and we need not to create a loop which saves time.
Also, do not make Statement object static in second case as the query for each execution will be different based on id passed as parameter.

Categories