java当中JDBC当中请给出一个SQLServer DataSourc…

2019-10-08 09:13:34来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

java当中JDBC当中请给出一个SQLServer DataSource and SingleTon例子

[学习笔记]

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.csdn.net/qq_43650923/article/details/100655993

 


原文链接:https://www.cnblogs.com/haima1949/p/11622374.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:SpringBootSecurity学习(13)前后端分离版之JWT

下一篇:maven仓库之第二篇