Alon Shmiel
Alon Shmiel

Reputation: 7121

JAVA: get cell from table of mysql

I get a parameter is called 'id' in my function and want to print the cell of the name of this id row.

for example:

this is my table:

id     name        email
1      alon     [email protected]

I send to my function: func(1), so I want it to print 'alon'.

this is what I tried:

static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;

Upvotes: 1

Views: 1937

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213193

Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -

Use: -

ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
    System.out.println(my_rs.getString("name"));
}

As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.

Here's how you use it: -

PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();

while (my_rs.next()) {
    System.out.println(my_rs.getString("name"));
}

Upvotes: 2

Nick
Nick

Reputation: 2845

  1. Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
  2. If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

You need to use ResultSet.next() to navigate into the returned data:

if (my_rs.next()) {
  System.out.println(my_rs.getString("name"));
}

Upvotes: 2

Related Questions