mee123
mee123

Reputation: 21

SELECT statements in JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JOptionPane;


public class Main
{
public static void main (String[] args) throws Exception

{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con =       DriverManager.getConnection("jdbc:mysql://localhost:3306/convocation","root","");



int id_convo= Integer.parseInt(JOptionPane.showInputDialog(null,"Please Insert Student ConvoID"));

PreparedStatement statement = con.prepareStatement("select name, course from stud_details where id='"+id_convo+"' ");

ResultSet result = statement.executeQuery();

while(result.next())
{
    JOptionPane.showMessageDialog(null, result.getString(1) + " "+ result.getString(2));
}
}
}

Im having a problem with the statement where it only shows name and course. I dont know why for award it not showed. I already have it in the database and it only show the first two in the sql statement. Same if i do SELECET * . only the first two in the database will showed.

thanks

Upvotes: 1

Views: 1159

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201409

I don't know why award is not shown [sic].

Change your query from

select name, course

to

select name, course, award

and then

JOptionPane.showMessageDialog(null, result.getString(1) + " "
    + result.getString(2));

to

JOptionPane.showMessageDialog(null, result.getString(1) + " "
    + result.getString(2) + " " + result.getString(3));

Also, as of JDBC 4.0 and Java 6 you shouldn't need to register your JDBC driver with

Class.forName("com.mysql.jdbc.Driver").newInstance();

Edit

And, as noted in the comments, you really should use your PreparedStatement correctly by binding the parameter. Like,

PreparedStatement statement = con.prepareStatement(
    "select name, course from stud_details where id=?");
statement.setInt(1, id_convo);

Finally, don't forget to close() everything in a finally block.

Upvotes: 2

Ye Win
Ye Win

Reputation: 2098

If you already try wity SELECT *, it seen this problem is not in SELECT statement. This problem is in this code

JOptionPane.showMessageDialog(null, result.getString(1) + " "+ result.getString(2));.

If you understand result.getString() method, your problem will go away. Try with below explanation:

result.getString(1) is represent first column of your table.
result.getString(2) is represent second column of your table.
result.getString(3) is represent third column of your table.
etc.........
........
........

Upvotes: 0

Related Questions