how to receive just one result from a query in a mysql database?

Jaime Ramos :

i´ve been using java to connect to a remote database in mysql, i´ve done a lot of diferents queries but today i´ve figured out that every time i wanted to look for a result, i have been always storing the result/s in a resulset,although in some cases my queries just have to return 0 or 1 result,that means that is not possible to receive an array of registers that meet the querie, so what kind of variable should i use to store JUST ONE RESULT?

Below i will post a portion of my code that describe the situation, it have to be understood that in the table "tareas", every register have a DIFFERENT title, like a PK.

Thanks in advance...

ps = c.prepareStatement("SELECT * FROM tareas WHERE titulo='" + title + "'");
rr = ps.executeQuery();
while (rr.next()) {
    JOptionPane.showMessageDialog(null, "Titulo: " + rr.getString("titulo") + newline + 
              "Creador: " + rr.getString("nombre") + newline + 
              "Receptor: " + rr.getString("receptor") + newline + 
              "Tarea: " + nuevacadena(rr.getString("tarea")) + newline + 
              "fecha de creación:" + lafecha(rr.getString("fecha")));
}
Elliott Frisch :

Add a LIMIT; without that the JDBC driver may pre-fetch more than one row regardless of option 2 (which you can also do). That is,

ps = c.prepareStatement("SELECT * FROM tareas WHERE titulo='" + title + "' LIMIT 1");

and then change (for option 2)

while (rr.next())

to

if (rr.next())

Also, since you are using a PreparedStatement, you should bind your parameters instead of writing them literally into the query; for example,

ps = c.prepareStatement("SELECT * FROM tareas WHERE titulo=? LIMIT 1");
ps.setString(1, title);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132286&siteId=1