JSON in MySQL where condition - mysql

I have the following JSON List: '["Foo","Bar"]'
The following entries are in my MySQL table t
Name | Color
--------------
Foo | Red
Bar | Blue
Foobar | Green
Is there a way to use my JSON List as a condition in my where clause and get the same result like:
select * from t where name in ('Foo','Bar')
?

Akina solved it:
SELECT * FROM t WHERE JSON_CONTAINS( '["Foo","Bar"]', CONCAT('"', Name, '"') )

From my knowledge you can put multiple WHERE statements on a SQL query
See: https://www.w3schools.com/SQl/sql_where.asp
you just need to add a 'AND' or 'OR' after each condition
SELECT * FROM Customers
WHERE Country='Mexico'
AND Address='Avda. de la ConstituciĆ³n 2222'
OR Address='Mataderos 2312';
;
So you just build the string you need before using
with c# you can do something like (just AND operators):
public List<Data> ExecuteQueryAND(List<string> statements, string table)
{
// initial connection
// ...
string str = $"SELECT * FROM {table}\n";
for (int i =0; i > statements.Count; i++)
{
if( i == 0 )
{
str = str + $"WHERE {statements[i]}\n";
}
str = str + $"\tAND {statements[i]}\n";
}
str = str + ";";
Console.WriteLine("Sql Query: " + str);
// more code to execute sql
}
then when you call it:
// some code ..
FilterList = ExecuteQueryAND( new List<string> { "Access=\"ADMIN\""});
// more code ..

Related

using a string of values in WHERE clause - mysql

I have a string of values like :
$cat = "1,5,6,8,9";
now I would like to use that variable in WHERE clause. how do I do it ?
"select category from test where category...?"
I am using below code but I get null from number_of_result variable :
$array_of_cat = explode(",",$cat);
if($number_of_result == 0){
$mresult = mysql_query("select * from books where
GoodName like '%$title%' and GroupCode in ($array_of_cat) ");
$number_of_result = mysql_num_rows($mresult);
}
Change your SQL statement to this one. Use implode() to pass array elements in IN clause
$mresult = mysql_query("
SELECT * FROM books
WHERE GoodName LIKE '%$title%' AND GroupCode IN (" . implode(",", $array_of_cat) . ")");
You do not need to explode the variable - doing so results in an array that will result in the wrong value (the string "Array") when interpolated into the SQL string.
Despite the fact that this is unsafe (SQL injection prone) you could do:
if($number_of_result == 0){
$mresult = mysql_query("select * from books where
GoodName like '%$title%' and GroupCode in ($cat)");
$number_of_result = mysql_num_rows($mresult);
}
I strongly suggest you use the mysql_real_escape_string function to prepare your variables.
$cat = array(1,5,6,8,9);
$array_of_cat = implode(",",$cat);
if($number_of_result > 0){
$mresult = mysql_query("select * from books where
GoodName like '%$title%' and GroupCode in ($array_of_cat) ");
$number_of_result = mysql_num_rows($mresult);
}
Also, I'd strongly suggest reading up on PDO/MySQLi

How to perform a mysql statement with dynamic count of where clauses in java.sql

I have a jersey java server and a mysql server:
I send a POST with an ArrayList<Long> to the server. Then I want to do a select like ...where long OR long OR long....
Is there an elegant way to solve this problem and not to do always a single select in a for loop?
How can I form a sql-statement with dynamic count of where clauses?
Thank you very mutch.
Instead of OR multiple times, you can use IN with the where clause in the SQL query.
You can read ArrayList object in a loop and set the where clause values.
JAVA code snippet:
int paramCount = list.size();
StringBuilder sqlSelect = new StringBuilder( 1024 );
sqlSelect.append( "select x,y,z from my_table " );
if( paramCount > 0 ) {
sqlSelect.append( "where long_column in ( " );
for( i = 0; i < paramCount; i++ ) {
sqlSelect.append( ( i > 0 ? ", ?" : "?" );
} // for each param
sqlSelect.append( " )" );
} // if list is not empty
// make the prepare statement (pst) with the above sql string
// ...
// now set the parameter values in the query
int paramIndex = 1;
if( paramCount > 0 ) {
for( i = 0; i < paramCount; i++ ) {
pst.setLong( paramIndex++, ( (Long)list.get( i ) ).longValue() );
} // for each param
} // if list is not empty

Executing multiple COUNT queries in Java

I have a MySQL database (ver. 5.2 CE) and I have a table which I want to filter into a another table based on the WHERE conditions given by the user (this comes from an array list). I want to perform count query on this new table for a split chosen by the user. For example, COUNT(*) from TableName WHERE [userConditions like gender=male and gender=female, etc]. The user can give more than one WHERE conditions but the COUNT query will only take one condition at a time. Hence, I made my method (which performs this query) an array to return multiple queries based on the number of conditions chosen by the user and then execute each query in a for loop. However, this seems to give me compilation errors in 2 ways: i) the way I return a built string in a String[] method and ii) the way I execute the COUNT query. The code for these problems:
private String countQuery;
public SetupSubsamplePopulation(UserSelectedSplit split) {
this.split = split;
// connect to the database
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull","root", "sharadha_1992");
String buildSelectQuery = buildSelectQueryForCode();
String getRowsFromTable = getNumberOfRows();
stmt = connection.createStatement();
rows = stmt.executeUpdate(buildSelectQuery);
ResultSet rs = stmt.executeQuery(getRowsFromTable);
for (int i=0; i<getCountOfWhereCondition().length; i++){
//where I get the executeQuery error
ResultSet rs1= stmt.execute(getCountOfWhereCondition());
while (rs1.next()){
rowsCount= rs.getRow();
rows_count++;
}
}
while (rs.next()) {
rows = rs.getRow();
rows_inserted++;
}
System.out.println(rows_inserted);
System.out.println(rows_count);
} catch (Exception e) {
e.printStackTrace();
}
}
The method which returns the array of COUNT queries:
public String[] getCountOfWhereCondition() {
countQuery="SELECT COUNT (*) FROM (SELECT * from mygrist_samples.subsample_population WHERE ";
for (int i = 0; i < split.getSplitConditions().size(); i++) {
String getCorrespondingCodeFromDatabase = split.getSplitConditions().get(i).getCode();
getCorrespondingCodeFromDatabase = getCorrespondingCodeFromDatabase.replaceAll("-", "_");
Enumerations enum1 = new Enumerations();
String getCorrespondingRelationshipOperator = enum1.getOperator(split.getSplitConditions().get(i).getRelationship());
countQuery+=getCorrespondingCodeFromDatabase + " " + getCorrespondingRelationshipOperator + " '" + split.getSplitConditions().get(i).getAnswer() + "'";
}
countQuery+=")";
System.out.println(countQuery);
//error which doesn't allow me to return a string
return countQuery;
}
Can someone please tell me how to implement this sensibly? Thank you very much.
I think you want conditional aggregation rather than a where:
select count(*)
from mygrist_samples.subsample_population
WHERE XXX
Is the same as:
select sum(case when XXX then 1 else 0 end) as cnt1
from mygrist_samples.subsample_population
Now you can add multiple conditions on one call:
select sum(case when XXX then 1 else 0 end) as cnt1,
sum(case when yyy then 1 else 0 end) as cnt1
from mygrist_samples.subsample_population

mySQL "select" is case sensitive through JDBC but not through command line

I am trying to search my database using mySQL through JDBC. When I use this statement:
SELECT * FROM tablename WHERE name='joe';
It does a case insensitive search and returns any rows that have 'Joe' or 'joe', which is what I want. I ran select collation(version()), and this returned 'utf8_general_ci', which is apparently supposed to be case insensitive. However, when I run the same query using JDBC within my Java applet, it does a case sensitive search. Here is my query2 function:
try {
Vector<Vector<String>> out = new Vector<Vector<String>>() ;
Connection con = connect() ;
Statement statement = con.createStatement() ;
System.out.println( "SQL: " + s ) ;
ResultSet rs = statement.executeQuery(s) ;
while( rs.next() )
{
String r = rs.getString(1) ; // RS is indexed from 1
Vector<String> q = new Vector<String>() ;
for( int i = 2 ; i <= tableSize ; i ++ )
{
q.add(r) ;
r = rs.getString(i) ;
}
q.add(r) ;
out.add(q) ;
}
con.close() ;
return( out ) ;
} catch (SQLException e) {
System.err.println( "SQL EXCEPTION" ) ;
System.err.println( s ) ;
e.printStackTrace();
}
And here is my select function that calls query2:
public static Vector<Vector<String>> select( String table , List<String> columns , List<String> values )
{
String statement = "SELECT * from `" + table + "` WHERE " ;
for( int i = 0 ; i < columns.size(); i ++ )
{
statement += columns.get(i) + "='" + values.get(i) + "'" ;
if( i + 1 < columns.size() )
statement += " AND " ;
}
statement += " ;" ;
return query2 ( statement , tableSize(table) ) ;
}
Any idea how I can make this query case insensitive?
It turns out that the search I thought was using the select function was actually using a different function. This function was selecting everything from the database and sorting through it client-side. I tested the select function and it actually is case insensitive, without having to use any of the tips given (but thanks for the advice!).
Wouldn't this line need to read
statement += "UPPER("+columns.get(i) + ")='UPPER(" + values.get(i) + ")'"
downfall... can't use indexes since it's uppering everything.

GAS: How to use strings in databse querys?

I try to query in my script my database. The query's parameters depends on what I have defined in my GUI. Sometimes I like to use the NAME in query and sometimes the CITY. Here is the code:
var query = 'STRUCTTYPE: PERSON';
if (value1 != 0) {
query = query + ', NAME: ' + value1;
}
if (value2 != 0) {
query = query + ', CITY: ' + value2;
}
So the string 'query' itself is ok, but when I try to use it in db.query I get error message.
var results = db.query(query);
Any suggestions? Or other ways to handle this problem? Thanks!
The query parameter you pass to ScriptDb.query function must be an object, not a string. Try this:
var query = {STRUCTTYPE: 'PERSON'};
if( value1 != 0 ) //this != 0 seems a weird test, but I'm copying from your example
query.NAME = value1;
if( value2 != 0 )
query.CITY = value2;
var results = db.query(query);