import java.sql.*;
public class ConnectDB
{
Connection connect=null;
Statement statement=null;
ResultSet result=null;
String driver="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@192.168.1.22:1521:orac";
String user="scott";
String password="tiger";
String sql="select sno,sname,ssex,sage,sdept from student";
public void doConnect()
{
try
{
Class.forName(driver).newInstance();
System.out.println("加载驱动成功");
connect=DriverManager.getConnection(url,user,password);
System.out.println("连接数据库成功");
statement=connect.createStatement();
result=statement.executeQuery(sql);
result.next();
System.out.println("------记录------");
System.out.println("学号"+result.getString("sno"));
System.out.println("姓名"+result.getString("sname"));
System.out.println("性别"+result.getString("ssex"));
System.out.println("年龄"+result.getInt("sage"));
System.out.println("专业"+result.getString("sdept"));
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
connect.close();
statement.close();
result.close();
}
catch(Exception e)
{}
}
} public static void main(String[] args)
{
ConnectDB aa=new ConnectDB();
aa.doConnect();
}
}

解决方案 »

  1.   

    加判断
    if(result.next())

    System.out.println( "------记录------ "); 
    System.out.println( "学号 "+result.getString( "sno ")); 
    System.out.println( "姓名 "+result.getString( "sname ")); 
    System.out.println( "性别 "+result.getString( "ssex ")); 
    System.out.println( "年龄 "+result.getInt( "sage ")); 
    System.out.println( "专业 "+result.getString( "sdept ")); 
    }
      

  2.   

    next()方法会返回一个布尔值
    当结果集中有下一行数据时,返回true,否则返回false
    用循环可以全部读取result中的全部数据
    while(result.next()){
    System.out.println(   "------记录------   ");   
    System.out.println(   "学号   "+result.getString(   "sno   "));   
    System.out.println(   "姓名   "+result.getString(   "sname   "));   
    System.out.println(   "性别   "+result.getString(   "ssex   "));   
    System.out.println(   "年龄   "+result.getInt(   "sage   "));   
    System.out.println(   "专业   "+result.getString(   "sdept   "));   
    }