My problem is that I want to apply the following two commands in JavaFX in order to get how many 1ones are in a named "party" column from a database named "conteo".
sql ="select count(*) from conteo where party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
i used System.out.println(rs.getString("party")); to expect the correct number of 1ones in "party" column from "conteo" database and i get "the error column party do not exist", but actually it already exist!!!
sql ="select count(*) from conteo where party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
I would like to print in command line "rs" using "System.out.println()"
My database address is correctly address it, because i already write data sucessfully in mysql databases using javafx, how can i properly print "rs" result in command line?, anyhelp is appreciated, thanks in advance, Omar Torres
You asked...
how can i properly print "rs" result
Do you mean something like this...
if (rs.next()) {
int theCount = rs.getInt(1);
System.out.println(theCount);
}
You did not select the party column for the output. Since you're using a aggregate function, this shouldn't work in this case anyways. You'd need to use GROUPING BY+HAVING anyways.
It's much simpler to provide an alias for the value
sql ="SELECT COUNT(*) AS num FROM conteo WHERE party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
if (rs.next()) {
int i = rs.getInt("num");
...
}
or
sql ="SELECT COUNT(*) FROM conteo WHERE party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
if (rs.next()) {
int i = rs.getInt(1); // access first column in result
...
}
I am trying to pass array of cities to the IN clause but seems inverted commas are removed while preparing query
Here is the code
let city = ["Moscow", "Paris"];
let sql = 'SELECT* FROM cities WHERE city IN ('+city+')';
console.log(sql);
and in the console I am getting this
SELECT* FROM cities WHERE city IN (Moscow, Paris);
and thus getting exception while executing query!
Any help?
Try this, it will work
var sql = "SELECT uid FROM cities where city IN ('" + gender.join("','") + "')";
Result :-
SELECT uid FROM cities where city IN ('Male','Female')
Using a Query Builder is a preferable method but a possible solution if you have a long array:
let stringifiedValues = JSON.stringify(city).replace(/\[|\]/g,'');
let sql = `SELECT * FROM cities WHERE city IN (${stringifiedValues})`;
Use the map function to transform all items in your array. You want to add quotes to the items like this Moscow => 'Moscow'
Use the join to gather the transformed items into a string. The delimiter can be specified as an argument like this array.join(', ')
Use template literals (string interpolation) to inject your string in your query. Like this ${str}
const city = ["Moscow", "Paris"];
const injectedString = city.map(c => `'${c}'`).join(', ');
let sql = `SELECT * FROM cities WHERE city IN (${injectedString})`;
console.log(sql);
How can I select a row specific by string values
SELECT * FROM my_table WHERE name=
-- then some function to test what string it starts with
Its a bit hard to explain so i will explain an example with JavaScript
if(mystring.indexOf('targetstring') != -1){
// if that variable contains this string
}
if(mystring.indexOf('targetstring') == 0){
// if that variable starts with this string
}
So all in all, I want to select rows, when their name(a string column) starts with or contains a specific string.
You can use LIKE and the wildcard %:
SELECT * FROM my_table WHERE name LIKE 'john%'; /* name starts with john*/
SELECT * FROM my_table WHERE name LIKE '%john%'; /* name contains john*/
SELECT * FROM my_table WHERE name like "%string%"
I have procedure with a single string parameter to retrieve records from my table test which has two fields id(int) and Name(varchar).
the query in the procedure is shown below
Select * from test where id in (strParam);
and value in the parameter will be
strParam="1,2";
but the result will be wrong because query will be as shown below
Select * from test where id in ('1,2');
but i need the query to be like shown below
Select * from test where id in (1,2);
please help me with a solution
the programming language is C#
thanks,
suraj
Usually you construct the SQL correctly in your programming language:
Select * from test where id in ('1,2');
should come from your application code, where it's easier to change strParam="1,2"; to strParam="'1','2'":
Split (explode) the string into an array
escape each element in the array (using the correct MySQL-ESCAPE function)
Join (implode) the array back into a string,
If you really can't change the application code, maybe some SQL tricks could work. Try:
SELECT * FROM test where FIND_IN_SET(ID,strParam) > 0
Not sure if this is the most efficient way:
Explode the value strParam to an array and then build up the string you need in the query:
<?php
$arrayParam = explode(',', $strParam);
$strParamQuery = '(';
foreach ($arrayParam as $Param) {
if ($strParamQuery != '(') { $strParamQuery = $strParamQuery.','; //Add a comma to all but the first occurence
$strParamQuery = $strParamQuery.$param;
}
$strParamQuery = $strParamQuery.')';
$query = 'Select * from test where id in '.$strParamQuery.';';
?>
I am trying to accomplish the following. Let's say we have a table that contains these fields (ID, content)
1 | apple
2 | pineapple
3 | application
4 | nation
now, I am looking for a function that will tell me all possible common matches. For example, if the argument is "3", the function will return all possible strings from 3 characters that appear in more then one record.
In this case, I get "app","ppl","ple","ati","tio","ion"
If the argument is "4", i get: "appl","pple","atio","tion"
If the arugment is "5", i get: "apple","ation"
If the argument is "6", nohting is returned.
Untill now, I did not find a function that accomplishes this.
Thx!
Some extra information:
I am using this in a PHP script with a MySQL database. I really just want to give the amount of characters as an argument and of course the table to search in.
Well, this is kind of ugly, but it does work fine. It's generic SQL and will work in any environment. Simply generate a number of selects of a substring that is greater than the maximum length of the field that you're reading. Change the number 50 in the function to a number that exceeds your fieldlength. It may return a realllly long query, but like I said, it'll work fine. Here is an example in Python:
import sqlite3
c = sqlite3.connect('test.db')
c.execute('create table myTable (id integer, content varchar[50])')
for id, content in ((1,'apple'),(2,'pineapple'),(3,'application'),(4,'nation')):
c.execute('insert into myTable values (?,?)', [id,content])
c.commit();
def GenerateSQL(substrSize):
subqueries = ["select substr(content,%i,%i) AS substr, count(*) AS myCount from myTable where length(substr(content,%i,%i))=%i group by substr(content,%i,%i) " % (i,substrSize,i,substrSize,substrSize,i,substrSize) for i in range(50)]
sql = 'select substr FROM \n\t(' + '\n\tunion all '.join(subqueries) + ') \nGROUP BY substr HAVING sum(myCount) > 1'
return sql
print GenerateSQL(3)
print c.execute(GenerateSQL(3)).fetchall()
The query generated looks like:
select substr FROM
(select substr(content,0,3) AS substr, count(*) AS myCount from myTable where length(substr(content,0,3))=3 group by substr(content,0,3)
union all select substr(content,1,3) AS substr, count(*) AS myCount from myTable where length(substr(content,1,3))=3 group by substr(content,1,3)
union all select substr(content,2,3) AS substr, count(*) AS myCount from myTable where length(substr(content,2,3))=3 group by substr(content,2,3)
union all select substr(content,3,3) AS substr, count(*) AS myCount from myTable where length(substr(content,3,3))=3 group by substr(content,3,3)
union all select substr(content,4,3) AS substr, count(*) AS myCount from myTable where length(substr(content,4,3))=3 group by substr(content,4,3)
... )
GROUP BY substr HAVING sum(myCount) > 1
And the results it produces are:
[(u'app',), (u'ati',), (u'ion',), (u'nat',), (u'pin',), (u'ple',), (u'ppl',), (u'tio',)]
I'm sorry as I haven't been playing with php for a while & I don't have a proper test environment for it, but I quickly devised a way of doing this in c# 3.5
pseudocode: build a table with strings of the specified length & a count of occurences next to it. Select where count > 1:
static void Main(string[] args)
{
string[] data = { "apple", "pinapple", "application", "nation" };
string[] result = my_func(3,data);
foreach (string str in result)
{
Console.WriteLine(str);
}
Console.ReadKey();
}
private static string[] my_func(int l, string[] data)
{
Dictionary<string,int> dict = new Dictionary<string,int>();
foreach (string str in data)
{
for (int i = 0; i < str.Length - l + 1; i++)
{
string part = str.Substring(i, l);
if (dict.ContainsKey(part))
{
dict[part]++;
}else {
dict.Add(part,1);
}
}
}
var result = from k in dict.Keys
where dict[k] > 1
orderby dict[k] descending
select k;
return result.ToArray<string>();
}
One obvious option is to use REGEX. I have no prior experience in this but this might be of help to you:
http://dev.mysql.com/doc/refman/5.1/en/regexp.html
You'll need to find a suitable expression to match what you need.