JSmith
JSmith

Reputation: 4808

How can I search a string in some of the tables in a database using JDBC?

Lets say I have table person with different columns in a mysql database

the columnns are:

name, age, description, friends

I'm trying to find a way to search a certain string in the columns name, description and friends using jdbc in google app script.

The result should send me back in return an array containing all the lines matching my query

for example here is a database:

 ------------------------------------------
| name | age | description      | friends  |
 ------------------------------------------
| John | 20  | "I like Joe"     | Joe Jack |
| Joe  | 32  | "I like me"      | -        |
| Jack | 23  | "I like nothing" | -        |
 ------------------------------------------

if my query is Joe then line 1 and line 2 should be returned as Joe appears two times in line 1 and 1 time in line 2.

Here's for the moment what I use to get a line searching by name

 function getLine(name)
{
  var ret = {};
  var conn = Jdbc.getConnection(dbUrl, user, userPwd);
  var stmt = conn.createStatement();
  var res = stmt.executeQuery("SELECT * FROM item WHERE name='" + name + "'");
  var numCol = res.getMetaData().getColumnCount();
  var i = 0;
  while (res.next())
  {
    while (i < numCol)
    {
      ret[i]= res.getString(i + 1);
      i++;
    }
  }
  return (ret);
}

Upvotes: 0

Views: 88

Answers (1)

jose_bacoy
jose_bacoy

Reputation: 12684

Like and OR are the correct keyword for your query.

select *
from item
where name = 'Joe'
        or description like concat('%', 'Joe', '%')
        or friends like concat('%', 'Joe', '%');

Upvotes: 3

Related Questions