用Java實現資料庫應用系統

來源:互聯網
上載者:User

串連工廠,實現了DataSource介面

package skydev.modules.data;
import java.sql.*;
import javax.sql.DataSource;
import java.io.PrintWriter;
public class ConnectionFactory implements DataSource {
private String userName;
private String password;
private String driverName;
private String url;
private java.sql.Connection connection;

/**
* 根據設定的串連參數建立一個新的串連執行個體
* @return
*/
private Connection getNewConnection() {
try {
this.connection.close(); //試圖關閉串連
}
finally {
this.connection = null; //釋放串連
try {
Class.forName(this.driverName); //載入驅動程式
//DriverManager.registerDriver(driver);
try {
this.connection = DriverManager.getConnection(this.url, this.userName,
this.password);
}
catch (SQLException e) {
throw e;
}
}
finally {
return this.connection; //返回建立立的串連
}
}
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getDriverName() {
return driverName;
}

public void setDriverName(String driverName) {
this.driverName = driverName;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public java.sql.Connection getConnection() {
if (connection != null) {
try {
if (connection.isClosed()) {
connection = null;
getNewConnection();
}
}
catch (SQLException ex) {
}
}
if (connection == null) { //沒有設定串連則建立一個串連
getNewConnection();
}
return connection;
}

public Connection getConnection(String userName, String password) throws
SQLException {
this.setUserName(userName);
this.setPassword(password);
return getConnection();
}

public PrintWriter getLogWriter() {
return null;
}

public void setLogWriter(PrintWriter printWriter) {
}

public void setLoginTimeout(int int0) {
}

public int getLoginTimeout() {
return 0;
}
}

實現串連SQLServer的串連工廠,這裡因為我們的項目使用SQLServer2000所以只實現了SqlServerConnectionFactory。


package skydev.modules.data;
public final class SqlServerConnectionFactory extends ConnectionFactory {
private final String dbDriver ="com.microsoft.jdbc.sqlserver.SQLServerDriver";
private String host;//主機
private int port;//連接埠
private String databaseName;//Sql資料庫名稱

public SqlServerConnectionFactory() {
super.setDriverName(dbDriver);
}

/**
*
* @param host 資料庫所在的主機名稱:如"localhost"
* @param port SQL伺服器啟動並執行連接埠號碼,如果使用預設值 1433,傳入一個負數即可
* @param databaseName 資料庫名稱
* @param userName 使用者名稱
* @param password 口令
*/
public SqlServerConnectionFactory(String host,
int port,
String databaseName,
String userName,
String password) {
this.setHost(host);
this.setPort(port);
this.setDatabaseName(databaseName);
this.setUserName(userName);
this.setPassword(password);
init();
}

private void init() {
super.setDriverName(dbDriver);
super.setUrl("jdbc:microsoft:sqlserver://" + host.trim() + ":" +
new Integer(port).toString() + ";DatabaseName=" +
databaseName.trim());
//super.setUrl("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=demo");
}

public void setHost(String host) {
//處理主機名稱
if ( (host == null) || (host.equals("")) || (host.equals(".")) ||
(host.equals("local"))) {
host = "localhost";
}
int index = host.indexOf("//", 0);
if (index == 0) {
host = host.substring(2); //去掉前面的"//"
}
index = host.indexOf("//", 0);
if (index >= 0) {
try {
throw new Exception("SQL Server主機名稱參數錯誤!");
}
catch (Exception ex) {
}
}
this.host = host;
}

public void setPort(int port) {
/**
* 預設連接埠1433
*/
if (port < 0) {
port = 1433;
}
this.port = port;
}

public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
}

使用"sun.jdbc.odbc.JdbcOdbcDriver"串連資料庫的串連工廠
package skydev.modules.data;
public class JdbcOdbcConnectionFactory extends ConnectionFactory {
private final static String driveName = "sun.jdbc.odbc.JdbcOdbcDriver";
private String odbcName;

public JdbcOdbcConnectionFactory() {
super.setDriverName(driveName);
}

/**
*使用指定的Odbc資料來源串連資料庫伺服器
* @param odbcName
*/
public JdbcOdbcConnectionFactory(String odbcName) {
super.setDriverName(driveName);
setOdbcName(odbcName);
}

public void setOdbcName(String odbcName) {
this.odbcName = odbcName;
this.setUrl("jdbc:odbc:" + odbcName);
}
}

package skydev.modules.data;
import java.sql.*;
import java.sql.PreparedStatement;
import javax.sql.DataSource;

public abstract class DatabaseObject {
protected Connection connection = null;
protected ResultSet resultSet = null;
protected ResultSetMetaData resultSetMetaData = null;
private ConnectionFactory connectionFactory = null;
private java.sql.Statement statement=null;
private javax.sql.DataSource dataSource;//=new Statement();

public DatabaseObject(){
dataSource=null;
connection=null;
}

public DatabaseObject(ConnectionFactory connectionFactory) {
this.setConnectionFactory(connectionFactory);
this.dataSource=connectionFactory;//ConnectionFactory實現了DataSource介面
}

/**
* 執行查詢
* @param sql 要執行的Sql語句
* @return 返回查詢的結果集 ,查詢失敗返回null
*/
public ResultSet getResultSet(String sql) {
try {
this.resultSet = statement.executeQuery(sql); //保留內部指標
}
catch (SQLException e) {
e.printStackTrace();
this.resultSet = null;
}
finally {
return this.resultSet;
}
}

/**
* 擷取外部指定ResltSet的ResultSetMetaData資料
* @param resultSet 要擷取的ResultSet
* @return 失敗返回null
*/
public ResultSetMetaData getResultSetMetaData(ResultSet resultSet) {
ResultSetMetaData resultSetMetaData = null;
try {
resultSetMetaData = resultSet.getMetaData();
}
catch (SQLException e) {
e.printStackTrace();
resultSetMetaData = null;
}
finally {
return resultSetMetaData;
}
}

/**
* 擷取最近一次設定或者返回的ResultSet的ResultMetaData資料,
* 比方說調用了:getResultSet(sql)方法,然後調用getResultSetMetaData方法
* 可以獲得相應的ResultSetMetaData資料。
* @return
*/
public ResultSetMetaData getResultSetMetaData() {
return this.getResultSetMetaData(this.resultSet);
}

/**
* 執行預存程序
* @param spName 預存程序名稱
* @return
*/
public ResultSet Execute(String spName) {
//對此資料庫執行一個 SQL 查詢
ResultSet resultSet = null;
try {
// PreparedStatement stmt = (PreparedStatement) connection.createStatement();
resultSet = statement.executeQuery(spName);
}
catch (Exception e) {
System.out.println("execute error" + e.getMessage());
}
return resultSet;
}

/**
* 設定資料庫連接工廠,對此類的所有操作之前,必須調用該方法,
* 設定資料庫連接工廠。
* @param connectionFactory 資料庫連接工廠ConnectionFactory 類對象以及
* 衍生類別對象。
*/
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
connection = connectionFactory.getConnection();
try {
statement = connection.createStatement();
}
catch (SQLException ex) {
System.err.println(ex);
}
}

public Connection getConnection() {
return connection;
}

public java.sql.Statement getStatement() {
return statement;
}
public javax.sql.DataSource getDataSource() {
return dataSource;
}
}

  具體項目的資料庫訪問基類


package skydev.modules.data;
public class DbObject extends DatabaseObject {
// private final static String driveName = "sun.jdbc.obdc.JdbcOdbcDriver";
public DbObject() {
super(new SqlServerConnectionFactory("localhost", 1433, "TheSchool", "sa",""));
}

public DbObject(ConnectionFactory connectionFactory) {
super(connectionFactory);
}
}

在項目中的資料庫層中的資料庫訪問類都從DatabaseObject類派生,這樣只需要在一個地方設定資料連線,其他地方都不需要涉及資料庫訪問的具體串連代碼。

  如:User類專門負責Users組的許可權控制等,只需要簡單的代碼就可以串連並訪問資料庫了。這裡具體實 現與此文章無關,只舉一兩個模組做例子。


public class User extends DbObject {
public User() {
//子類也可以覆蓋基類的訪問方式,在單機調式時有用。
// super(new SqlServerConnectionFactory("localhost", 1433, "TheSchool", "sa",""));
super();//調用基類的資料庫存取碼。
}
/*
在做資訊系統時為了提高客維護性,我們一般使用預存程序返回和修改資料,在資料庫層代碼不使用

Select語句直接檢索資料,做到資料庫層代碼的最大的靈活性和可維護性。一旦發現需要修改資料庫中的

代碼,只需要修改村年初過程即可以。
下面介紹Java使用SqlServer StoreProcedure的方法。
預存程序的參數使用“?”代替,下面的代碼有一定的代表性,預存程序有輸入參數,輸出參數。
預存程序的準系統為:檢測userID和encPassword是否和資料庫儲存的一致,返回UserID,如果不一

致返回-1。
*/
//測試資料庫中儲存的已經加密的密碼和使用者傳入的加密的密碼是否一致。
public boolean testPassword(int userID, byte[] encPassword) {
Connection con = this.getConnection();
CallableStatement cs = null;
try {
cs = con.prepareCall("{?=call sp_Accounts_TestPassword(?,?)}");
cs.setInt(2, userID);
cs.setBytes(3, encPassword);
cs.registerOutParameter(1, Types.INTEGER); //@UserID
cs.execute();
if (cs.getInt(1) == 1) { //密碼合格
return true;
}
else {
return false;
}
}
catch (SQLException ex) {
return false;
}
catch (Exception e) {
return false;
}
}
}

 

來源:http://blog.csdn.net/chensheng913/archive/2004/07/11/39256.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.