5.SQLServer DataSource and SingleTon:
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) {
}
}
}
更多请看下节:https://blog.youkuaiyun.com/qq_43650923/article/details/100655993
本文介绍了一种使用JDBC驱动实现SQL Server单例数据源的方法,通过Singleton模式确保了在整个应用程序中数据源的唯一性,提高了资源利用效率。文章提供了完整的代码示例,包括数据源的初始化和获取连接的过程,并通过测试程序验证了单例模式的有效性。
789

被折叠的 条评论
为什么被折叠?



