How can i get another string from select query? - java

I want to get string from column no. 4 from my database to check user privileges.
Can I use rs.getString(index) to get data from column no.4?
I want to check user´s privileges...so if the column data is equal 4, the page will be redirected to AdminControlPanel.jsp
BUT, this code doesn´t work :(
String user=request.getParameter("login");
String pass=request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/android","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from users where login='"+user+"' and password='"+pass+"'");
String p = rs.getString(4);
int count=0;
while(rs.next()){
count++;
}
if(count>0 && p == "4"){
// out.println(rs);
response.sendRedirect("AdminControlPanel.jsp");
}
else{
out.println("aaa");
response.sendRedirect("#");
}
}
catch(Exception e){
System.out.println(e);
}

you are comparing two String objects rather than checking the values in the String.
just change the code to p.equals("4") and try.

String p = rs.getString(4); // This should be inside your while
int count=0;
while(rs.next()){
count++;
}
You should move your first line inside your while loop. You can't
fetch the columns of a row, until you move your cursor to that row
using res.next().
Also, since your database should ideally have only one record for a
combination of username and password. So, you can better use an
if instead of while.
And you don't really need a count variable there.
So, your code should be: -
ResultSet rs=st.executeQuery("select * from users where login='"+user+"' " +
"and password='"+pass+"'");
if (rs.next()) {
String p = rs.getString(4); // Note that using Column name is a better idea
// or rs.getInt(4) if the column type is `int`
if(p.equals("4")) { // Use equals method to compare string content
response.sendRedirect("AdminControlPanel.jsp");
} else{
out.println("aaa");
response.sendRedirect("#");
}
}
Also, note that you should compare your string using equals method. if (p == "4") will give you false result. == operator does not compare the content of the string, rather the content of the reference used in comparison.

You want
while (rs.next()) {
String val = rs.getString(4);
....
Note that iterating through a ResultSet iterates through the rows. For each row, the column indexing starts from '1'.
However it's safer to get by column name, since your SQL query doesn't specify neither the columns nor the order in which they're returned:
String val = rs.getString("COLUMN_NAME");
I see from the below that you need an integer. Check out the doc for ResultSet for more info, but:
int val = rs.getInt("COLUMN_NAME");
As an aside, I don't see you closing your ResultSet/Statement/Connection in the above. If you're not, then you'll need to!

Related

String query = "SELECT sum(Cardhundred)FROM Dialog"; [duplicate]

This question already has an answer here:
How to retrieve sum of a column of data from the database?
(1 answer)
Closed 4 years ago.
Currently trying to get sum of the integers of a column called Cardhundred, I does not proceed the answer, can somebody suggest me an idea to get the total of all integers in my column?
I want to get the sum from a column in access database, the column from which I want to get the sum, has all integers value not double or float, and I have done some code for that which gives me no result, it means the text field which supposed to display the result is empty.
This is my code:
if(showtotal.isSelected()) {
try {
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://E:\\Mydb.accdb");
Statement st = conn.createStatement();
String query = "SELECT sum(Cardhundred)FROM Dialog";
ResultSet rs=st.executeQuery(query);
if(rs.next()) {
String total=rs.getString("sum(Cardhundred)");
showdate.setText(""+total+"");
}
} catch(Exception e){ }
}
There are two ways to solve this: use the column index (rather than the name) then you don't need to worry about the name of the expression:
int total = rs.getInt(1);
The column numbering in JDBC starts with 1, not with 0 as with arrays in Java.
Alternatively, use a column alias in your query:
String query = "SELECT sum(Cardhundred) as total_number FROM Dialog";
Then use that alias to get the value:
int total = rs.getInt("total_number");

Building PreparedStatement in Java With Variable Number of Columns for Inserting Data into Database [duplicate]

This question already has answers here:
How to insert values in a table with dynamic columns Jdbc/Mysql
(2 answers)
Closed 5 years ago.
What is a good design pattern to achieve this without endless code?
Given the scenario whereby the user may input 1...100 columns, maybe 23 one time, 32 on another insert, and 99 fields on another insert etc. All of which may be different fields each time too.
The PreparedStatement in Java needs to know what column names to enter first, how many ?'s to put into the values part of the INSERT query, the data types of the database field names to ensure the correct setInt and setString etc are entered.
For less than around 10 columns, you can kind of get around this challenge with the following logic;
1) If variableEnteredForFieldName is not null, then append to the relevant parts of the query in the form of a String builder type setup;
fieldName_1
?
2) Do the same for all entered field names
3) Strip out the final trailing , that will naturally be present in both the field names and the ?s
4) Create the PreparedStatement
5) Run through the same input parameters again to determine of the variableEnteredForFieldName is not null, if not null, then run a setInt or setString based on the known data type that the database requires and set this to the correct index number for the ?s.
As long as the query builder logic and the query filler logic have the names/values in the correct order in part 1 and part 2, then all works well. It does however mean duplicating the entire code that relates to this logic, one for generating the SQL to use when creating the PreparedStatement and another for filling the PreparedStatement.
This is manageable for a small number of input parameters, but this soon gets unmanageable for larger number of input parameters.
Is there a better design pattern to achieve the same logic?
The code below is an outline of all of the above for reference;
String fieldName1 = request.getParameter("fieldName1");
String fieldName2 = request.getParameter("fieldName2");
//Build Query
String fieldNames = "";
String fieldQuestionMarks = "";
if (fieldName1 != null) {
fieldNames = fieldNames + " FIELD_NAME_1 ,";
fieldQuestionMarks = fieldQuestionMarks + " ? ,";
}
if (fieldName2 != null) {
fieldNames = fieldNames + " FIELD_NAME_2 ,";
fieldQuestionMarks = fieldQuestionMarks + " ? ,";
}
//Trim the trailing ,
fieldNames = fieldNames.substring(1, fieldNames.length() - 1);
fieldQuestionMarks = fieldQuestionMarks.substring(1, fieldQuestionMarks.length() - 1);
try {
String completeCreateQuery = "INSERT INTO TABLE_NAME ( " + fieldNames + " ) VALUES ( " + fieldQuestionMarks + " );";
Connection con = DriverManager.getConnection(connectionURL, user, password);
PreparedStatement preparedStatement = con.prepareStatement(completeCreateQuery);
int parameterIndex = 1;
//Fill Query
if (fieldName1 != null) {
preparedStatement.setString(parameterIndex, fieldName1);
parameterIndex++;
}
if (fieldName2 != null) {
preparedStatement.setInt(parameterIndex, Integer.parseInt(fieldName2));
parameterIndex++;
}
}
As you can see, it's do-able. But even with just 2 optional fields, this code is huge.
The way I see it, if user is able to omit any of the columns from the list, then all columns are optional, and can be safely set to NULL during an insert. Therefore, all you need is one prepared statement with the "monster" INSERT, with all columns listed; then during the actual insert operation, you loop though the user-provided data, setting values for the columns provided, and calling setNull() for omitted columns. You'll need to maintain a structure somewhere (your DAO class most likely) mapping column names to their order in the SQL statement.

[sqlite MISMATCH]: data type mismatch

i'm getting an sqlite mismatch exception while inserting data into database.i m creating an app in netbeans but when i try to update database by selecting textfields by clicking button its showing this exception.
private void calculationDBActionPerformed(java.awt.event.ActionEvent evt) {
String sql2 = "Insert into Calculation_Info (prodID,item_name,net_amount,tax_rate,Amt_Of_Product,Grand_Total) values(?,?,?,?,?,?)";
try{
pst = conn.prepareStatement(sql2);
pst.setString(1, prodID.getText());
pst.setString(2, txtPRoduct.getText());
pst.setString(3, txtTotal.getText());
pst.setString(4, txtTaxTotal.getText());
pst.setString(5, txtAmountTotal.getText());
pst.setString(6, txtGrandTotal.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Gotcha Bro!");
pst.close();
rs.close();
}catch(Exception exc){
JOptionPane.showMessageDialog(null, exc);
}
}
You can't set String for an Int of real type, for that you get this type of error, so you have to convert your inputs to the right type, for example :
prodID.getText() should be an int and not a String so you have to use it like so:
pst.setInt(1, Integer.parseInt(prodID.getText()));
//--^^^^^----------^^convert your String to int and change setString to setInt
The same thing for the rest.
#YCF_L explains the problem correctly. I believe the issue that you have #Muhammad Quanit is that you are not understanding what your query is asking for and what you're trying to pass into the query.
To break it down for you, your query:
"Insert into Calculation_Info (prodID,item_name,net_amount,tax_rate,Amt_Of_Product,Grand_Total) values(?,?,?,?,?,?)"
Takes 6 values that you have to provide (Please NOTE the type of each they take in):
prodID (int)
item_name(String)
net_amount(double)
tax_rate(BigDecimal)
Amt_Of_Product(int)
Grand_Total(BigDecimal)
In your program, you have 6 text boxes that will obtain these values to put in HOWEVER when you call the method: getText() it returns a String type. So when we try to put String prodID = "3" into our SQL query, you would receive the error you originally received: datatype mismatch. Now your current problem is: java.lang.numberFormatException : for input String. This means that you are trying to convert a String value into a number; however it is FAILING. So what could be possible reasons for this? Well...
/* Lets say I have a string with value 4.7*/
String s = "4.7";
/* Lets try to parse this using parseInt method*/
Integer.parseInt(s); //NumberFormatException -- because 4.7 cannot be converted into an int
/* How about if my string was a word/phrase?*/
String s = "foo";
/* Attempt to parse...*/
Integer.parseInt(s); //NumberFormatException -- because "foo" cannot be converted into integer
Double.parseDouble(s); //NumberFormatException -- because "foo" cannot be converted into a double
So as you can see, you have to be very careful and keep track of what you are converting and passing into your query (and vice versa).
As #YCF_L mentioned, perhaps your String contains white spaces at the start or end. There is a method called trim() in the String class that will help you with that.
/* Let's call the getText() method to obtain our string */
String s = item_name.getText(); // s = " Foo Bar "
/* NOTE: the white spaces (' ') BEFORE and AFTER the String we want*/
System.out.println(s.trim()); // Prints out "Foo Bar"
So the String OBJECT has a method called trim() which gets rid of TRAILING and LEADING white spaces, but NOT white spaces in between. So instead of getting " Foo Bar ", we will get "Foo Bar".
I upvoted #YCF_L 's answer -- he deserves the credit. I just wanted you to understand this concept since you were still confused after his explanation followed by receiving the NumberFormatException.
Editted to include the trim() method that was mentioned in the comments.

Efficient way to compare input Data with Sql table in Java

First of all I will explain my use case:
I will get a String Array of names from user(Can of size 2,5,1)
e.g Suppose user input is like this:
String[] names={"Micheal", "Joe","Jim"}
Now after taking input from user, I have to hit SQL table called "USERS" and check whether all of these names are present in USERS table or not. If any single name is not present then return false. If all names are present in USERS table then return true.
My Idea:
My idea is to hit USERS table. Get all names of USERS table in a String array (named as all_names) and then compare my input string(i.e names) with this all_names String. So if names is subset of all_names then return true else return false.
Problem:
But I think this is not an efficient solution. When this table will expand then I will have thousands of records so this technique will be very exhaustive. Any other better and efficient solution for this please.
Updated Solution:
Suppose names in USERS table are unique.
Thanks for your replies. Now I have adopted this approach after getting help from your answers. I want to know that this solution is a better approach or not:
String[] names={"Micheal","Jim","Joe"};
String list2string = StringUtils.join(names, ", ");
//connection was established previosuly
stmt = conn.createStatement();
System.out.println(list2string);
rs = stmt.executeQuery("SELECT COUNT(*) AS rowcount FROM USERS WHERE name IN (" +
list2string +
")");
rs.next();
int count = rs.getInt("rowcount");
rs.close();
if(names.length==count){
System.out.println("All names are in users table");
}else{
System.out.println("All names are not present in users table");
}
Want your comments on this updated solution please.
Regards
You are right, this is not really efficient.
It is the database job to do such things.
You can either make a select statement for each name, eg.
SELECT name FROM users WHERE name = 'Micheal'
or
SELECT name FROM users WHERE name IN ('Micheal', 'Joe', 'Jim')
and check the returned rows.
It might be quiet different depending on which framework you use to query the database.
you can form a string out of string array using loop
for example if you have string array like this:
String[] names={"Micheal", "Joe","Jim"}
get a string lets say s -> "Micheal", "Joe","Jim"
now query like this:
String sql = SELECT name FROM users WHERE name IN (" + s + ")". (you can check the format).
get the output collection and compare with the given collection.
One way to do it, could be
SELECT
COUNT(DISTINCT name)
FROM
users
WHERE
name IN ('Micheal', 'Joe', 'Jim')
Then check if the count is equal to your parameter count, in our case, we should get 3.
I will get a String Array of names from user(Can of size 2,5,1)
You get the input from user, you hit the database with query:
SELECT (WHATEVER_YOU_NEED) FROM SCHEMA_NAME.TABLE_NAME WHERE COLUMN IN
(USER_PROVIDED_INPUT);
You store this result in List.
Get all names of USERS table in a String array (named as all_names)
and then compare my input string(i.e names) with this all_names
String. So if names is subset of all_names then return true else
return false.
Yes, you are right, so you will use
Use Collection.containsAll():
boolean isSubset = listA.containsAll(listB);
And, if your database has unique names (which I guess can be duplicate), you can simply get the count from SQL Query and match it with the user input.
I hope this will help.
SELECT IF(
( SELECT COUNT(DISTINCT name) FROM users WHERE name IN ({toSearch}) ) = {Count},
, 1 , 0
) as Result
replace {toSearch} with e.g. 'Micheal', 'Joe', 'Jim'
{count} is the number of searche, in this example 3. so if all exist the column "Result" has the value 1 else 0

Get 2 consecutive rows of a resultset

I need to compare a row of a ResultSet with the consecutive row if the row string matches a particular string.
while(rs.next())
{
String name = rs.getString("name");
if(name.equalsIgnoreCase("SomeName")
{
String nextName = //code to get the next consecutive row
if(nextName.contains(name)
{
name = "NA";
}
}
stringList.add(name);
}
How can I get the next row while the cursor is still on that row?
Approach hint: try storing the first one in a variable and then compare when reading the next row.
Really teaching you how to fish here, not handing you the catch.
To flesh this out (a little):
String lastName = null;
while (rs.next()) {
// do stuff with this row
if (name.equalsIgnoreCase("SomeName") && lastName != null) {
// work with lastName & SomeName
}
// save/assign lastName
}
You can use rs.next(), rs.getString() and then rs.previous() to move one row forward.
However a better option would be to memorize previous string value in a local variable and compare it at the next iteration.
Hint: Try to store first row value then use another loop and compare that value.
Hint: use nested loop

Categories