connectbean.java
来自「J2EE指南」· Java 代码 · 共 57 行
JAVA
57 行
package Tools;
import java.sql.*;
public class ConnectBean {
private static Connection con = null;
private static void startConnect(String driver,String dataSource,String username,String password)
throws RuntimeException{
try{
Class.forName(driver);
System.out.println ("loadDriver");
con = DriverManager.getConnection(dataSource,username,password);
System.out.println ("getConnection");
}
catch(Exception e){
throw new RuntimeException(e);
}
}
public static Connection getConnection()throws RuntimeException{
if(con==null){
throw new RuntimeException("Connection is null");
}
return con;
}
public static void setConnection(String driver,String dataSource,String username,String password)
throws RuntimeException{
try{
startConnect(driver,dataSource,username,password);
}
catch(Exception e){
throw new RuntimeException(e);
}
}
public static void closeConnection() throws RuntimeException{
try{
con.close();
}
catch(Exception e){
throw new RuntimeException(e);
}
}
public static void main(String arge[]){
//测试数据
try{
ConnectBean.setConnection("sun.jdbc.odbc.JdbcOdbcDriver","jdbc:odbc:MyDataSource","sa","");
Connection con = ConnectBean.getConnection();
Statement stat = con.createStatement();
ResultSet result = stat.executeQuery("select * from login");
System.out.println (result.next());
while(result.next()){
String s = result.getString(1);
System.out.println (s);
}
}
catch(Exception e){
System.out.println (e);
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?