1

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;

3 Answers 3

2

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"));
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

2
  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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.