Encapsulates a Java database access management class _java

Source: Internet
Author: User
Tags getmessage odbc
Copy Code code as follows:

Package com.groundhog.codingmouse;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
/**
* Database Management class
* @author Codingmouse
* 2009.2.20
*/
Public final class Dbmanager {
/**
* Database Connection objects
*/
Private Connection dbconnection = null;
/**
* Database Command Execution Object
*/
Private PreparedStatement prestatement = null;
/**
* Result Set Object
*/
Private ResultSet rsset = null;
/**
* Database-driven version number
*/
private static String driverversion = null;
/**
* Database server login username and password string constants (default values are
To ' sa ')
*/
private static String Databaseuser = "sa";
private static String DatabasePassWord = "sa";
/**
* Database-Driven full class name string constants
*/
private static Final String
driver_class_sqlserver2000 =
"Com.microsoft.jdbc.sqlserver.SQLServerDriver"; Sql
Server 2000 Direct Connection
private static Final String
driver_class_sqlserver2005 =
"Com.microsoft.sqlserver.jdbc.SQLServerDriver"; Sql
Server 2005 Direct Connection
private static Final String
Driver_class_bridgeconnect = "Sun.jdbc.odbc.JdbcOdbcDriver";
ODBC Bridge Connection
/**
* Database connection string Constants
*/
private static Final String
database_url_sqlserver2000 =
"Jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=stud
B "; SQL Server 2000 Direct connection
private static Final String
database_url_sqlserver2005 =
"Jdbc:sqlserver://127.0.0.1:1433;databasename=studb";
SQL Server 2005 Direct connection
private static Final String
Database_url_bridgeconnect = "Jdbc:odbc:stuDBSource";
ODBC Bridge Connection
/**
* Define the instance static variables of the class itself (for use in the case of a singleton [piece] pattern)
*/
private static Dbmanager ConnectionManager = null;
/**
* Privatization default construction (for use in single case [piece] mode application, prevent class being straight
Then instantiated with the New keyword)
*/
Private Dbmanager () {
Super ();
}
/**
* Methods for obtaining database connection management class instances (application of single case [piece] mode)
* @param version Database driver number, value: (Version =
2000 | Version = 2005 | Version = ODBC)
* @param user Database server logon username
* @param password Database server login password
* @return Database Connection Management Objects
* @throws Exception Parameter Error exception
*/
public static Dbmanager getinstance (
String version,
String User,
String password)
Throws Exception {
if (!) ( Version = = "2000" | | Version = = "2005"
|| Version = = "ODBC")) {
throw new Exception ("database-driven version number
Incorrect, the value can only be "2000/2005/ODBC"! ");
}
Save Database driver version number
DriverVersion = version;
if (user = null | | user.equals ("")) {
throw new Exception ("Database server login
User name cannot be empty! ");
}
Save Database Server login username and password
Databaseuser = user;
DatabasePassWord = password;
Apply a singleton [piece] pattern to ensure that the class itself has only one instance
if (ConnectionManager = = null) {
ConnectionManager = new Dbmanager ();
}
Returns an instance of the class itself
return ConnectionManager;
}
/**
* Ways to get a database connection
* @return Database Connection objects
*/
Private Connection getconnection () {
try {
Class.forName (
DriverVersion = =
"2000"
?
driver_class_sqlserver2000
: (DriverVersion = =
"2005"
?
driver_class_sqlserver2005
:
Driver_class_bridgeconnect));
This.dbconnection =
Drivermanager.getconnection (
DriverVersion = =
"2000"
?
database_url_sqlserver2000
: (DriverVersion = =
"2005"
?
database_url_sqlserver2005
:
Database_url_bridgeconnect),
Databaseuser,
DatabasePassWord);
catch (ClassNotFoundException ex) {
SYSTEM.ERR.PRINTLN ("SQL Server not Found"
"+ driverversion +" database-driven class: "+ Ex.getmessage ());
Output exception stack information on console
Ex.printstacktrace ();
catch (Exception ex) {
SYSTEM.ERR.PRINTLN ("Get Database connection Error")
Error: "+ ex.getmessage ());
Output exception stack information on console
Ex.printstacktrace ();
}
Return database Connection objects
return this.dbconnection;
}
/**
* Methods to get database command execution objects
* @param SQL command assembly statement string to execute
* @return Database Command execution object
*/
Private PreparedStatement Getpreparedstatement
(String SQL) {
try {
To create a database from a obtained database connection object
Command execution Object
This.prestatement = getconnection
(). preparestatement (SQL);
catch (Exception ex) {
SYSTEM.ERR.PRINTLN ("Get Database command
Row Object Error: "+ ex.getmessage ());
Output exception stack information on console
Ex.printstacktrace ();
}
Returns the database command execution object
return this.prestatement;
}
/**
* Execute UPDATE statement (insert| update| Delete)
* @param SQL command assembly statement string to execute
* @return The number of rows affected
*/
public int executeupdate (String sql) {
try {
Empty the original content of the result set object
This.rsset = null;
Executes the statement and returns the number of affected rows
Return this.getpreparedstatement
(SQL). Executeupdate ();
catch (SQLException e) {
SYSTEM.ERR.PRINTLN ("Update data error:" +
E.getmessage ());
return 0;
}finally{
To close a database connection resource
Closedbresource ();
}
}
/**
* Execute Query Statement (Select)
* @param SQL command assembly statement string to execute
* @return The result set object after the query
*/
Public ResultSet executequery (String sql) {
try {
Empty the original content of the result set object
This.rsset = null;
Execute the SQL statement to get the result set
This.rsset =
This.getpreparedstatement (SQL). ExecuteQuery ();
catch (SQLException e) {
SYSTEM.ERR.PRINTLN ("Query data error:" +
E.getmessage ());
}
Return result Set Object
return this.rsset;
}
/**
* Gets the number of record bars that return the result set after executing the specified SQL statement
* @param SQL command assembly statement string to execute
* @return The number of records obtained from the query results
*/
public int getresultsetcount (String sql) {
To save a counter variable that returns the number of rows after a specified SQL statement has been executed
int count = 0;
try {
Empty the original content of the result set object
This.rsset = null;
Execute the SQL statement to get the result set
This.rsset = This.getpreparedstatement
(SQL). ExecuteQuery ();
Iterate through the result set and accumulate the counter
while (This.rsSet.next ()) {
count++;
}
catch (SQLException e) {
E.printstacktrace ();
}
return count;
}
/**
* Close database connection resources (including result set objects, command execution objects, even
Access Object)
*/
public void Closedbresource () {
try {
Closeresultset ();
Closepreparedstatement ();
CloseConnection ();
catch (SQLException Sqlex) {
System.err.println (sqlex.getmessage
());
Output exception stack information on console
Sqlex.printstacktrace ();
}
}
/**
* methods to close result set objects
* @throws SQLException
*/
private void Closeresultset () throws SQLException {
try {
if (This.rsset!= null) {
This.rsSet.close ();
This.rsset = null;
}
catch (SQLException Sqlex) {
throw new SQLException ("Close result set pair
Like error: "+ sqlex.getmessage ());
Output exception stack information on console
Sqlex.printstacktrace ();
}
}
/**
* Methods to close database command execution objects
* @throws SQLException
*/
private void Closepreparedstatement () throws
SQLException {
try {
if (this.prestatement!= null) {
This.preStatement.close ();
This.prestatement = null;
}
catch (SQLException Sqlex) {
throw new SQLException ("Shutdown Database Life
Make the Execution object error: "+ sqlex.getmessage ());
Output exception stack information on console
Sqlex.printstacktrace ();
}
}
/**
* Methods to close the database connection
* @throws SQLException
*/
private void CloseConnection () throws SQLException {
try {
if (this.dbconnection!= null && (!)
This.dbConnection.isClosed ()) {
This.dbConnection.close ();
}
catch (SQLException Sqlex) {
throw new SQLException ("Close the database company
Connect error: "+ sqlex.getmessage ());
Output exception stack information on console
Sqlex.printstacktrace ();
}
}
}
Related Article

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.