Jdbc connection code in java

Source: Internet
Author: User

JDBC (Java Database Connectivity) is a Java API that can execute SQL statements. It can be used to operate different databases.

# JDBC driver: standard SQL statements can be transplanted between different databases, but the actual communication protocol of the database and some database features cannot be transplanted. Therefore, there must be another layer between JDBC and the database, it is used to map JDBC calls to specific database calls. This special layer is the JDBC driver.

There are four common JDBC drivers:

JDBC-ODBC bridge, is the first implementation of the JDBC driver, in order to quickly promote JDBC, non-multithreading, limited capacity, the driver will be jdbc api ing ODBC API

Directly map JDBC APIs to database-specific client APIs. This driver contains the local code of a specific database and can be used by clients of a specific database.

Supports three-tier JDBC access, mainly used in the Applet stage, accessing the database through the Applet

Pure java, directly interacting with database instances, smart, know the underlying protocols used by the database, is currently the most popular JDBC driver

Java JDBC connection code:

The Code is as follows: Copy code

Import java. io. InputStream;
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. ResultSet;
Import java. SQL. SQLException;
Import java. SQL. Statement;
Import java. util. Properties;
Public class JDBConnection {
Public Connection conn = null; // The instance that declares the Connection object
Public Statement stmt = null; // instance for declaring the Statement object
Public ResultSet rs = null; // declare an instance of the ResultSet object
// Define the variable for saving the database driver
Private static String dbClassName = "com. microsoft. jdbc. sqlserver. SQLServerDriver ";
Private static String dbUrl = "jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = DB_ATM ";
Private static String dbUser = "sa ";
Private static String dbPwd = "sa ";
Public JDBConnection (String propertyFileName) {// construction method with attribute file name
Properties prop = new Properties (); // property set object
InputStream is = null;
Try {
Is = JDBConnection. class. getClassLoader (). getResourceAsStream (
PropertyFileName); // attribute file input stream
// Is = new FileInputStream ("src/" + propertyFileName );
Prop. load (is); // load the property file stream to the Properties object
Is. close (); // close the stream
DbClassName = prop. getProperty ("dbClassName ");
DbUrl = prop. getProperty ("dbUrl ");
DbUser = prop. getProperty ("dbUser ");
DbPwd = prop. getProperty ("dbPwd ");
} Catch (Exception e ){
System. out. println ("Property file" + propertyFileName + "failed to open! ");
}
Try {
Class. forName (dbClassName); // 1. register the driver
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
}
Public JDBConnection () {// default constructor without Parameters
Try {
Class. forName (dbClassName); // 1. register the driver
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
}
Public static Connection getConnection (){
Connection conn = null;
Try {
// Class. forName (dbClassName); // 1. register the driver
// 2. Establish a connection with the database
Conn = DriverManager. getConnection (dbUrl, dbUser, dbPwd );
} Catch (Exception ee ){
Ee. printStackTrace ();
}
If (conn = null ){
System. err. println ("Warning: DbConnectionManager. getConnection () failed to get the database link.
\ R \ n link type :"
+ DbClassName
+ "\ R \ n link location :"
+ DbUrl
+ "\ R \ n user/password"
+ DbUser + "/" + dbPwd );
}
Return conn;
}
/*
* Function: execute a query statement.
*/
Public ResultSet executeQuery (String SQL ){
Try {// capture exceptions
// Call the getConnection () method to construct an instance conn of the Connection object
Conn = getConnection ();
Stmt = conn. createStatement (ResultSet. TYPE_SCROLL_INSENSITIVE, // 3. Create statement
ResultSet. CONCUR_READ_ONLY );
Rs = stmt.exe cuteQuery (SQL); // 4. Execute the query
} Catch (SQLException ex ){
System. err. println (ex. getMessage (); // output exception information
}
Return rs; // return result set object 5. Result Processing
}
/*
* Function: Perform the update operation.
*/
Public int executeUpdate (String SQL ){
Int result = 0; // defines the variable for storing the returned value.
Try {// capture exceptions
// Call the getConnection () method to construct an instance conn of the Connection object
Conn = getConnection ();
Stmt = conn. createStatement (ResultSet. TYPE_SCROLL_INSENSITIVE,
ResultSet. CONCUR_READ_ONLY );
Result = stmt.exe cuteUpdate (SQL); // execute the update operation
} Catch (SQLException ex ){
Result = 0; // assign the variable that saves the returned value to 0.
}
Return result; // return the variable that saves the returned value.
}
/*
* Function: Disable the database connection.
*/
Public void close () {// 6. Release the resource
Try {// capture exceptions
Try {
If (rs! = Null) {// when the rs of the ResultSet object instance is not empty
Rs. close (); // close the ResultSet object
}
} Finally {
Try {
If (stmt! = Null) {// when the instance stmt of the Statement object is not empty
Stmt. close (); // close the Statement object
}
} Finally {
If (conn! = Null) {// when the instance conn of the Connection object is not empty
Conn. close (); // close the Connection object
}
}
}
} Catch (Exception e ){
E. printStackTrace (System. err); // output exception information
}
}
}

Some property files that you need to pay attention:


DbClassName = com. microsoft. jdbc. sqlserver. SQLServerDriver
DbClassName2 = com. mysql. jdbc. Driver
DbPwd = sa
DbPwd2 = root
DbUrl = jdbc \: microsoft \: sqlserver \: // localhost \: 1433; DatabaseName \ = DB_ATM
DbUrl2 = jdbc \: mysql \:/// localhost \: 3306/db_atm
DbUser = sa
DbUser2 = root

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.