一个简单的问题~!

Pol 2007-11-21 09:24:00
我想把以下代码放在一个class 中,其它地方直接调用就行了,怎么做?
我自己弄的老是出错了.

Connection con=null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:mydb","sa","19861219");
}catch(Exception e1){
JOptionPane.showMessageDialog(null,e1.getMessage(),"数据库连接错误!",2);
}


就这些了.
我这样调用了":
try{
String sql="select * from BasicInfo b,PersonalInfo p where (b.cStudentNo=p.cStudentNo) and ?=?";
PreparedStatement stat =con.prepareStatement(sql);
stat.setString(1,"cStudentNo");
stat.setString(1,str2);
ResultSet rs=stat.executeQuery();
}catch(SQLException e){
JOptionPane.showMessageDialog(null,e.getMessage(),"错误",2);
}

能给出详细代码么?谢谢了.
...全文
44 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
shaoml 2007-11-21
  • 打赏
  • 举报
回复
public class Test{
public Connection con;

public Connection getConnection(){

try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver ");
con=DriverManager.getConnection( "jdbc:odbc:mydb ", "sa ", "19861219 ");


}catch(Exception e1){
JOptionPane.showMessageDialog(null,e1.getMessage(), "数据库连接错误! ",2);
}
return con;
}

调用时,new 出这个类的一个对象就行了。然后调用他的getConnection()方法
Test sqltest=new Test();
Connection con=sqltest.getConnection;
lmx8757921 2007-11-21
  • 打赏
  • 举报
回复
public Connection getConnection (){
Connection con=null;
try{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver ");
con=DriverManager.getConnection( "jdbc:odbc:mydb ", "sa ", "19861219 ");
}catch(Exception e1){
JOptionPane.showMessageDialog(null,e1.getMessage(), "数据库连接错误! ",2);
}
return con;
}


//你的另外一个方法:
try{
String sql= "select * from BasicInfo b,PersonalInfo p where (b.cStudentNo=p.cStudentNo) and ?=? ";
//CONNECTION
Connection con= getConnection ();

PreparedStatement stat =con.prepareStatement(sql);
stat.setString(1, "cStudentNo ");
stat.setString(1,str2);
ResultSet rs=stat.executeQuery();
}catch(SQLException e){
JOptionPane.showMessageDialog(null,e.getMessage(), "错误 ",2);
}
Pol 2007-11-21
  • 打赏
  • 举报
回复
谢谢您们两位了,我已解决了,和您们的差不多了.
这是数据库连接部分了.
import java.sql.*;
import javax.swing.JOptionPane;
public class DataConnection {
Connection con=null;
PreparedStatement stat=null;
Statement stmt=null;
ResultSet rs=null;
String sql="";

public DataConnection() {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:mydb","sa","");
stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
}catch(Exception e){
System.out.println(e.getMessage());
}
}

}
调用时DataConnection conn=new DataConnection();
conn.stat.....

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧