Efficient way to compare input Data with Sql table in Java - 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

Related

Java pagination issue print Printwriter

I tried to do a pagination in Java using PrintWriter. I used this as model: https://www.javatpoint.com/pagination-in-servlet.
As you can see in the example code is done in order to work with 3 pages and 5 elements each page.
out.print("<a href='ViewServlet?page=1'>1</a> ");
out.print("<a href='ViewServlet?page=2'>2</a> ");
out.print("<a href='ViewServlet?page=3'>3</a> ");
int total=5;
I don't think it makes any sense to copy all my code since reading from database works.. I just want to have 1 element on each page and have as many pages as elements was found.
So I use
String query = "select * from tabL where name like CONCAT( '%',?,'%') limit "
+ (start-1)+","+total;
with 1 for start and 1 for total..
ResulSet will have size 1 but if I use this
out.print("<a href='ViewServlet?page=1'>1</a> ");
out.print("<a href='ViewServlet?page=2'>2</a> ");
out.print("<a href='ViewServlet?page=3'>3</a> ");
It prints other elements as well.
So please help how could be done to have as many pages as elements are found and 1 element each page.
Do I need to have a select without limit and use the size of resulset obtained with that, is there a better solution ?
PS: someone please explain me how if I put limit with 1,1 ResulSet has size 1 but it can print 3 elements at least.
I would need to know at least the exact number of elements which were retrieved even with limit 1.
Thank you.
To find the total count you can use a count-query:
String countQuery = "select count(*) from tabL where name like CONCAT( '%',?,'%')";
When you execute this query with the same parameter as the query for the data you will get a ResultSet with one row and one column.
You can retrieve it with
Connection con = ...; // you probably already have a Connection
PreparedStatement ps = con.prepareStatement(countQuery);
ps.setString(1, name); // the name pattern that you're searching for
ResultSet rs = ps.executeQuery();
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}

Getting WHERE clause after Update statement

I am required to fetch the where clause after an update statement e.g.
UPDATE user_accounts SET bio='This is my bio' WHERE user_id = 1 OR name = 'Alex';
At the moment, I am able to get everything after the where clause with the following code:
String query = "UPDATE user_accounts SET bio='This is my bio' WHERE user_id = 1 OR name = 'Alex'";
int index = query.toUpperCase().indexOf("WHERE");
if (index != -1) {
System.out.println(query.substring(index));
}
But then I discovered that this was significantly flawed, since these sample queries would fail:
UPDATE user_accounts SET bio='This is where my bio is' WHERE user_id = 1 OR name = 'Alex';
UPDATE user_accounts SET whereColumn='' WHERE user_id = 1 OR name = 'Alex'
UPDATE user_whereabouts SET columnName='' WHERE user_id = 1 OR name = 'Alex'
Essentially, this fails if table name or any column name or column value under SET contains the word 'where' (case insensitive).
My thinking has currently been along the lines of a regex that does the following:
Checks if the word where is in between ' ' or " " (e.g. bio = "This is where my bio is") and skips it to move to the one which isn't inside the quotes. This will help eliminate the where words found in the SET values. Of course the Java quotes surrounding a string do not apply since they aren't part of the string itself.
Checks that the word where is sandwiched between spaces (e.g. ... WHERE ...). This will help eliminate the where words found in either table name or column name (SQL syntax itself can't allow table name or column name to solely be a reserved word).
Finally, returns the index of the wanted WHERE in order to get the substring (The objective of the question).
I am not very conversant with regexes and thus, I am in need of assistance. Please note that any other ways of achieving the objective will be highly appreciated as well.
You need some kind of SQL parser because regexes will fail short in many cases (for instance what if the where clause has a sub-select?)
I've never tried it but JSQLParser seems like a good solution
Using JSqlParser this would look like:
List<String> sqls = Arrays.asList("UPDATE user_accounts SET bio='This is my bio' WHERE user_id = 1 OR name = 'Alex';",
"UPDATE user_accounts SET whereColumn='' WHERE user_id = 1 OR name = 'Alex'",
"UPDATE user_whereabouts SET columnName='' WHERE user_id = 1 OR name = 'Alex'");
for (String sql : sqls) {
Statement stmt = CCJSqlParserUtil.parse(sql);
Update update = (Update)stmt;
System.out.println("sql=" + stmt.toString());
System.out.println(" where=" + update.getWhere());
}
However you could improve your where search by using regular expressions, e.g. for with word boudaries:
\bwhere\b
but again you are right, this version is flawed as well for e.g. set col = ' test where test'.
The right way to do it, is to parse the whole sql via a parser (https://github.com/JSQLParser/JSqlParser).

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.

I need help to select a distinct column values in android query builder

This is the query:
SELECT _id AS suggest_intent_data_id, _id,distinct word as suggest_text_1
FROM words WHERE (suggest_text_1 like "a%") ORDER BY word LIMIT 10.
but it is showing me error near disticnt.
This query works in sqlite manager in firefox:
SELECT distinct word as suggest_text_1
FROM words WHERE (suggest_text_1 like "a%") ORDER BY word LIMIT 10.
but i need the result from first query.
Here is is the code for query builder.
private static HashMap<String,String> buildColumnMap()
{
HashMap<String,String> map = new HashMap<String,String>();
map.put(SearchManager.SUGGEST_COLUMN_TEXT_1, "word as "+SearchManager.SUGGEST_COLUMN_TEXT_1);
map.put(BaseColumns._ID, "_id");
// map.put(SearchManager.SUGGEST_COLUMN_TEXT_2,"meaning as "+SearchManager.SUGGEST_COLUMN_TEXT_2);
map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "_id AS " +
SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
return map;
}
i solved the problem, i just added group by clause to the query and it worked.
select _id AS suggest_intent_data_id, _id, word as suggest_text_1
FROM words WHERE (suggest_text_1 like "a%") group by word order by word limit 10
You should perform a select distinct (by row) and not by "row cell"
SELECT distinct id AS suggest_intent_data_id, _id, word as suggest_text_1
FROM words WHERE (suggest_text_1 like "a%")
ORDER BY word LIMIT 10;

How can i get another string from select query?

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!

Categories