单例模式在项目中,很多地方多会用到,这里介绍一下直接使用Android调用SqlServer2008存储过程中用到的
Connection,其实这也就是用到了JAVA中连接数据库的jdbc驱动做的。为了避免项目中多处使用实例化Connection,故采用单例的设计模式。
public class GetConnection {
private static java.sql.Connection mConnect;
private static String TAG = "Connection";
public static java.sql.Connection getInstance() {
if (mConnect == null) {
synchronized (GetConnection.class) {
//双层线程锁
if (mConnect == null) {
try {
Log.d(TAG, "Connect instance");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
mConnect = DriverManager.getConnection(
"jdbc:jtds:sqlserver://" + URL.IP + ":1433/"
+ URL.DB + ";charset=unicode",
URL.USER, URL.PWD);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, "没有JDBC支持");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, "SQLServer无法连接");
}
}
}
}
return mConnect;
}
}
在这里最主要是体现单例模式,而不在于存储过程的调用,具体调用SQL存储过程的调用可以在网上搜索。