李惠玥最美考生照片:Java数据库异常问题

来源:百度文库 编辑:高校问答 时间:2024/04/26 19:13:41
我进行数据库边接时老是出现这样的问题,请哪个高手指点一下。
我写了一个类DataControl进行数据操作,能通过编译。

然后写了另外一类引用以上类进行数据库操作,代码如下:
import java.sql.*;
class Data{

public static void main(String[] args){

DataControl data=new DataControl();
String content=new String("微生物学");
String sql=new String("select BookName,Author,Publisher,Version,Price,ISBN,Content from book where bookname='"+ content+"'");
ResultSet rs=null;

rs=data.SQLSelect(sql);

int i=0;
while(rs.next()){
String Sname = rs.getString(1);
String Sno = rs.getString(2);
String Sage = rs.getString(3);
String Ssex = rs.getString(4);
String Sdept = rs.getString(5);
System.out.println(Sname+" "+Sno+" "+Sage+" "+Ssex+" "+Sdept);
i++;

}

System.out.println("共找到"+i+"项结果。");
data.SQLClose();
}

}
不能通过编译,报错如下:
D:\Test\WEB-INF\classes\Date.java:15: unreported exception java.sql.SQLException; must be caught or declared to be thrown
while(rs.next()){
^
D:\Test\WEB-INF\classes\Date.java:16: unreported exception java.sql.SQLException; must be caught or declared to be thrown
String Sname = rs.getString(1);
^
D:\Test\WEB-INF\classes\Date.java:17: unreported exception java.sql.SQLException; must be caught or declared to be thrown
String Sno = rs.getString(2);
^
D:\Test\WEB-INF\classes\Date.java:18: unreported exception java.sql.SQLException; must be caught or declared to be thrown
String Sage = rs.getString(3);
^
D:\Test\WEB-INF\classes\Date.java:19: unreported exception java.sql.SQLException; must be caught or declared to be thrown
String Ssex = rs.getString(4);
^
D:\Test\WEB-INF\classes\Date.java:20: unreported exception java.sql.SQLException; must be caught or declared to be thrown
String Sdept = rs.getString(5);
^
6 errors
数据源设定好了,两个类在同一个文件夹下。
请大家帮忙解决一下。
谢了!

修改原代码,捕获sql异常就可以了
try{
while(rs.next()){
String Sname = rs.getString(1);
String Sno = rs.getString(2);
String Sage = rs.getString(3);
String Ssex = rs.getString(4);
String Sdept = rs.getString(5);
}
}catch(Exception e){
System.out.println("发生SQL异常!");
}

import java.sql.*;
class Data
{
public static void main(String[] args)
{
DataControl data=new DataControl();
String content=new String("微生物学");
try
{
String sql=new String("select BookName,Author,Publisher,Version,Price,ISBN,Content from book where bookname='"+ content+"'");
ResultSet rs=null;
rs=data.SQLSelect(sql);
int i=0;
while(rs.next())
{
String Sname = rs.getString(1);
String Sno = rs.getString(2);
String Sage = rs.getString(3);
String Ssex = rs.getString(4);
String Sdept = rs.getString(5);
System.out.println(Sname+" "+Sno+" "+Sage+" "+Ssex+" "+Sdept);
i++;
}
}
catch (Exception e)
{
System.out.println("共找到"+i+"项结果。");
e.printStackTrace();
}
finally
{
data.SQLClose();
}
}
}