JDBC当中请给出一个SQLServer DataSource and SingleTon例子
SQLServer DataSource and SingleTon:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
import net.sourceforge.jtds.jdbcx.*;
import java.sql.*;
import javax.sql.*;
public class SqlserverSingletonDataSource {
static private JtdsDataSource ds;
private Connection con;
private SqlserverSingletonDataSource() {
try {
ds = new JtdsDataSource();
ds.setServerName("localhost");
ds.setDatabaseName("pubs");
ds.setUser("sa");
ds.setPassword("");
}
catch (Exception e) {
}
}
public static Connection getConnection() throws Exception {
if (ds == null) {
new SqlserverSingletonDataSource();
}
Connection con =null;
try {
con = ds.getConnection();
} catch (SQLException ex) {
}
return con;
}
}
测试程序:
/*when you use single step to debug the program, you can find that Singleton only
is executed once.*/
import java.sql.*;
import javax.sql.*;
public class testSqlserverSingletonDataSource {
public static void main(String args[]) {
Connection con;
try {
con = SqlserverSingletonDataSource.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from authors");
while (rs.next()) {
System.out.print(rs.getString("au_id") + " ");
System.out.println(rs.getString("au_lname"));
}
}
catch (Exception e) {
}
System.out.println("the following is the second time ");
try {
con = SqlserverSingletonDataSource.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from authors");
while (rs.next()) {
System.out.print(rs.getString("au_id") + " ");
System.out.println(rs.getString("au_lname"));
}
}
catch (Exception e) {
}
}
}
result is:
172-32-1176 White
213-46-8915 Green
238-95-7766 Carson
267-41-2394 O'Leary
274-80-9391 Straight
}
}