Package skydev.modules.data;
Import java.sql. *;
/ ** * Method using ODBC:
* "Sun.jdbc.odbc.jdbcodbcdriver"
* "JDBC: ODBC:" ODBCNAME
* * "Oracle.thin.driver"
* "QWe.sql.qWemysqldriver
*" Symantec.dbanywhere.driver
* * Access MS SQLServer method
* Drivename = "com.microsoft.jdbc.sqlser.sqlserverdriver";
* URL = "JDBC: Microsoft: SQLServer: // localhost: 1433; DatabaseName = DEMO";
* Access Mysql method:
* dbdriver = com.mysql.jdbc.driver
* URL = JDBC: Mysql: // localhost / demo
* /
Public Abstract Class AbstractConnectionFactory {
Private string username; private string password; private string drivername; private string Url; private java.sql.connection connection; / ** * factory method, return the actual created connection object * @return * /
/ ** * 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 connection Try {class.forname (this.drivername); // load driver try {this.connection = drivermanager.getconnection (this.URL, this.user, this.password);} catch (sqlexception e) { Throw e;}} finally {return this.connection; // Return to the newly established connection}}}}}
Public string getUsername () {return username;}
Public void setusername (string username) {this.username = usrname;}
Public string getpassword () {return password;}
Public void setpassword (string password) {this.password = password;}
Public string getDrivername () {returnidrName;} 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) {}}} == NULL) {// No setup is created, create a connection getNewconnection ();}
Return Connection;
}
Package skydev.modules.data;
Public Class ConnectionFactory Extens AbstractConnectionFactory {
Public connectionFactory () {}
Package skydev.modules.data;
Import java.sql. *; import java.sql.preparedStatement;
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; // = new Statement ();
Public DatabaseObject () {}
Public DatabaseObject (ConnectionFactory ConnectionFactory) {this.setConnectionFactory (connectionFactory);}
/ ** * Execute Query * @Param SQL To execute the SQL statement * @return returns the result set of queries, the query fails returns null * / public resultset getResultSet (String SQL) {// statement stmt = null; try {// stmt = connection.createStatement (); this.resultSet = statement.executeQuery (sql); // internal pointer reserved} catch (SQLException e) {e.printStackTrace (); this.resultSet = null;} finally {return this.resultSet; }
/ ** * Gets the ResultSetMetaData ResltSet externally specified data to be acquired * @param resultSet ResultSet * @return else return null * / public ResultSetMetaData getResultSetMetaData (ResultSet resultSet) {ResultSetMetaData resultSetMetaData = null; try {resultSetMetaData = resultSet.getMetaData (); } catch (SQLException e) {e.printStackTrace (); resultSetMetaData = null;} finally {return resultSetMetaData;}} / ** * Get the most recent data set or return the ResultSet ResultMetaData, say calls *: getResultSet (sql The method, then call the GetResultSetMetadata method * to get the corresponding ResultSetMetAdata data. * @Return * / public resultsetMetadata getResultSetMetadata () {return this.getResultSetMetadata (this.Resultset);}
/ ** * * @param spName execute a stored procedure stored procedure name * @return * / public ResultSet Execute (String spName) {// this database to perform a SQL query ResultSet resultSet = null; try {// PreparedStatement stmt = (PreparedStatement ); resultset = statement.executeQuery (spname);} catch (exception e) {system.out.println ("Execute Error" E.getMessage ());} Return ResultSet;
/ ** * Set the database connection factory before all the operations of this class must call this method, * Set the database connection plant. * @Param ConnectionFactory Database Connection Factory ConnectionFactory class object and * 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
Public Java.sql.Statement getStatement () {return statement;}} package sukydev.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);}} 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;
Public SQLServerConnectionFactory () {super.SetDrivername (dbdriver);
/ ** * * @Param Host Database The host name of the database: If the "localhost" * @Param port number running, if the default value is 1433, it will be introduced into a negative number * @PARAM DATABASENAME database name * @ param userName * @param password username 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: 1433; DatabaseName =Demo");} public void setHost (String host) {// Host Name IF ((Host == Null) || (Host.equals (")) || (Host.equals (")) || (Host.equals ("local"))) {host = "localhost" }
INDEX = host.indexof ("//", 0); if (index == 0) {Host = host.substring (2); // Remove the front "//"}
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 databaseename) {this.databaseName = DatabaseName;
}
Package skydev.modules.data;
Import junit.framework. *; import java.sql. *;
Public Class TestsqlSerConnectionFactory Extends TestCase {Private SqlServerConnectionFactory SQLServerConnectionFactory = NULL;
Protected void setup () throws exception {super.setup (); / ** @ Todo verify the constructors * / sqlserverConnectionFactory = new SQLServerConnectionFactory ();
Protected void teardown () throws exception {sqlserverConnectionFactory = NULL; super.teardown () ()
public void testEmpty () {// assertTrue (objCon.connectDatabase ()); assertEquals (sqlServerConnectionFactory.getDriverName (), "com.microsoft.jdbc.sqlserver.SQLServerDriver");} public void testDB1 () {
DbObject DbO = new DbObject (new SqlServerConnectionFactory ( "localhost", 1433, "demo", "sa", "")); Connection con = DbO.getConnection (); CallableStatement pstmt = null; System.out.println ( "TestDB1 () .......... "); / * try {PSTMT = Con.PrepareCall (" {call sp_getstudentbyid (?)} "); PSTMT.Setint (1, 1);} * / Try {PSTMT = Con.PrepareCall ("{call sp_getstudentbyname); PSTMT.SetString (1," Tom ");}
Catch (Sqlexception EX1) {system.out.println (exception ex) {system.out.println (ex);
ResultSet results = null; ResultSetMetaData resultMetaData = null; try {// results = DbO.getResultSet ( "sp_getStudentByName"); results = pstmt.executeQuery (); resultMetaData = DbO.getResultSetMetaData (results); int cols = resultMetaData.getColumnCount () String resultrow = "/ n field / n"; for (int i = 1; i <= cols; i ) {resultrow = resultmetata.getColumnname (i) ";";} system.out.println (resultrow) WHILE (results.next ()) {resultrow = "/ n content / n"; for (int i = 1; i <= cols; i ) {try = results.getstring (i) ";" ;} Catch (nullpointerexception e) {system.out.println (E.getMessage ());}} system.out.println (resultrow);}} catch (sqlexception ex) {}}
public void testDB2 () {DbObject DbO = new DbObject (new SqlServerConnectionFactory ( "localhost", 1433, "demo", "sa", "")); //DbO.setConnectionFactory(new SqlServerConnectionFactory ()); // Connection con = Dbo.getConnection (); system.out.println ("testdb2 () ........."); ResultSet Results = null; ResultSetMetadata ResultMetadata = null; try {results = dbo.getResultset ("SELECT * From persentsons; "); resultmetata = dbo.getResultSetMetadata (); int coLs = resultmetadata.getColumnCount (); string resultrow =" / n field / n "; for (int i = 1; i <= color; i ) {Resultrow = Resultmetata.getColumnName (i) ";";} system.out.println (resultrow); while (results.next ()) {resultrow = "/ n content / n"; for (int i = 1; i <= cols; i ) {Try {Resultrow = Results.getstring (i) ";";} catch (nullpointers) {system.out.println (E.getMessage ());}} SYST Em.out.println (resultrow);}} catch (sqlexception ex) {}} public void testdb3 () {
DbObject DbO = new DbObject (new SqlServerConnectionFactory ( "localhost", 1433, "demo", "sa", "")); Connection con = DbO.getConnection (); CallableStatement pstmt = null; System.out.println ( "TestDB3 () .......... "); try {pstmt = con?preparecall (" {= call sp_insertstudent (?,?,?)} "); Pstmt.setstring (2," zengqingsong "); PSTMT.Setint (3, 22);
PSTMT.RegisterOutparameter (4, Types.integer); PSTMT.RegisterOutParameter (1, Types.Iteger); int RET = PSTMT.ExecuteUpdate (); // Performing the number of rows of rows Int Ret2 = pstmt.Getint (1); // Return parameter (output parameters) int ID = pstmt.getint (4); // Output parameter system.out.Println (RET); system.out.println (RET2); system.out.println (ID);}
Catch (Sqlexception EX1) {system.out.println (exception ex) {system.out.println (ex);
}
}