Use Java to implement a database application system

Source: Internet
Author: User

Connect to the factory and implement the DataSource Interface

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;

/**
* Create a new connection instance based on the set connection Parameters
* @ Return
*/
Private Connection getNewConnection (){
Try {
This. connection. close (); // try to close the connection
}
Finally {
This. connection = null; // release the connection
Try {
Class. forName (this. driverName); // load the driver
// DriverManager. registerDriver (driver );
Try {
This. connection = DriverManager. getConnection (this. url, this. userName,
This. password );
}
Catch (SQLException e ){
Throw e;
}
}
Finally {
Return this. connection; // return the newly established 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) {// if no connection is set, a connection is created.
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;
}
}

Implement the connection factory to connect to SQLServer. Here, because our project uses SQLServer2000, only SqlServerConnectionFactory is implemented.


Package skydev. modules. data;
Public final class SqlServerConnectionFactory extends ConnectionFactory {
Private final String dbDriver = "com. microsoft. jdbc. sqlserver. SQLServerDriver ";
Private String host; // host
Private int port; // port
Private String databaseName; // sqldatabase name

Public SqlServerConnectionFactory (){
Super. setDriverName (dbDriver );
}

/**
*
* @ Param host the host Name of the database, for example, "localhost"
* @ Param port the port number running on the SQL server. If the default value is 1433, enter a negative number.
* @ Param databaseName Database Name
* @ Param userName: 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 ){
// Process Host Name
If (host = null) | (host. equals ("") | (host. equals (".") |
(Host. equals ("local "))){
Host = "localhost ";
}
Int index = host. indexOf ("//", 0 );
If (index = 0 ){
Host = host. substring (2); // remove the preceding "//"
}
Index = host. indexOf ("//", 0 );
If (index> = 0 ){
Try {
Throw new Exception ("SQL Server host name parameter error! ");
}
Catch (Exception ex ){
}
}
This. host = host;
}

Public void setPort (int port ){
/**
* Default port 1433
*/
If (port <0 ){
Port = 1433;
}
This. port = port;
}

Public void setDatabaseName (String databaseName ){
This. databaseName = databaseName;
}
}

Use "sun. jdbc. odbc. JdbcOdbcDriver" to connect to the database connection Factory
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 );
}

/**
* Use the specified Odbc data source to connect to the Database Server
* @ 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 implements the DataSource Interface
}

/**
* Query execution
* @ Param SQL the SQL statement to be executed
* @ Return returns the query result set. If the query fails, null is returned.
*/
Public ResultSet getResultSet (String SQL ){
Try {
This. resultSet = statement.exe cuteQuery (SQL); // keep internal pointer
}
Catch (SQLException e ){
E. printStackTrace ();
This. resultSet = null;
}
Finally {
Return this. resultSet;
}
}

/**
* Obtain ResultSetMetaData of the specified external ResltSet
* @ Param resultSet the ResultSet to be obtained
* @ Return: return null if a failure occurs.
*/
Public ResultSetMetaData getResultSetMetaData (ResultSet resultSet ){
ResultSetMetaData resultSetMetaData = null;
Try {
ResultSetMetaData = resultSet. getMetaData ();
}
Catch (SQLException e ){
E. printStackTrace ();
ResultSetMetaData = null;
}
Finally {
Return resultSetMetaData;
}
}

/**
* Obtain the ResultMetaData of the last set or returned ResultSet,
* For example, The getResultSet (SQL) method is called and the getResultSetMetaData method is called.
* Obtain the corresponding ResultSetMetaData.
* @ Return
*/
Public ResultSetMetaData getResultSetMetaData (){
Return this. getResultSetMetaData (this. resultSet );
}

/**
* Execute the Stored Procedure
* @ Param spName: name of the stored procedure
* @ Return
*/
Public ResultSet Execute (String spName ){
// Execute an SQL query for this database
ResultSet resultSet = null;
Try {
// PreparedStatement stmt = (PreparedStatement) connection. createStatement ();
ResultSet = statement.exe cuteQuery (spName );
}
Catch (Exception e ){
System. out. println ("execute error" + e. getMessage ());
}
Return resultSet;
}

/**
* Set the database connection factory. This method must be called before all such operations,
* Set the database connection factory.
* @ Param connectionFactory database connection factory ConnectionFactory Class Object and
* A derived class object.
*/
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;
}
}

Database Access Base class for specific projects


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 );
}
}

In the database layer of the project, the Database Connector class is derived from the DatabaseObject class. In this way, you only need to set the data connection in one place, and the specific connection code involving database access is not required in other places.

For example, the User class is responsible for Users Group permission control. You only need simple code to connect to and access the database. The specific implementation here has nothing to do with this article. Only one or two modules are used as an example.


Public class User extends DbObject {
Public User (){
// Subclass can also overwrite the access mode of the base class, which is useful in standalone mode.
// Super (new SqlServerConnectionFactory ("localhost", 1433, "TheSchool", "sa ",""));
Super (); // call the database access code of the base class.
}
/*
In order to improve the maintenance of customers, we usually use stored procedures to return and modify data, and do not use the database-layer code.

The Select statement directly retrieves data, maximizing the flexibility and maintainability of the database-layer code. Once you find that you need to modify

Code, you only need to modify the village at the beginning of the year.
The following describes how to use SqlServer StoreProcedure in Java.
The stored procedure parameters use "?" Instead, the following code is representative. Stored Procedures include input parameters and output parameters.
The basic functions of the stored procedure are as follows: Check whether userID and encPassword are consistent with those stored in the database and return UserID. If they are different

Returns-1.
*/
// Test whether the encrypted password stored in the database is consistent with the encrypted password entered by the user.
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.exe cute ();
If (cs. getInt (1) = 1) {// pass the password
Return true;
}
Else {
Return false;
}
}
Catch (sqlexception ex ){
Return false;
}
Catch (exception e ){
Return false;
}
}
}

 

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.