JDBC中的SELECT语句

时间:2014-12-24 03:50:52

标签: java sql 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));
}
}
}

我的声明有问题,它只显示名称和课程。我不知道为什么奖项没有显示。我已经在数据库中拥有它,它只显示sql语句中的前两个。如果我做SELECET *也一样。只显示数据库中的前两个。

感谢

2 个答案:

答案 0 :(得分:2)

  

我不知道为什么奖项没有显示[原文如此]。

更改您的查询
select name, course

select name, course, award

然后

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

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

此外,从JDBC 4.0和Java 6开始,您不需要使用

注册JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver").newInstance();

修改

并且,正如评论中所述,您确实应该通过绑定参数来正确使用PreparedStatement 。像,

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

最后,不要忘记在close()区块中finally所有内容。

答案 1 :(得分:0)

如果你已经尝试过了SELECT *,那么就会发现这个问题不在SELECT语句中。 此问题出现在此代码中

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

如果您了解result.getString()方法,您的问题就会消失。 尝试以下解释:

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