欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-08 15:38:05
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) {
}

}

}

文章转载自原文: