JDBC Fourth time Learning

Source: Internet
Author: User
Tags time in milliseconds

Preach Intelligence podcast Li Yong's JDBC series learning finally close to the end, so happy, can learn so many things, not to hurry to record down, left to aftertaste!

How to use open Source project DBCP (common in actual projects)

It consists of three steps:

    1. A jar package that must be used with DBCP.
    2. Add the DBCP configuration file.
    3. Java API:BasicDataSourceFactory.createDataSource (prop);

Otherwise it will report an exception:

Java.lang.ClassNotFoundException:org.apache.commons.logging.LogFactory

The primary reason is that the import of this jar problem will be solved because the Commons-logging.jar is imported less!

The DBCP configuration file (dbcpconfig.properties) is as follows:

#连接设置driverclassname =com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/jdbcusername=rootpassword= Yezi#<!--Initialize the connection--initialsize=10#最大连接数量maxactive =50#<!--maximum idle connection--Maxidle=20#<!--minimum idle connection--Minidle=5#<!--timeout wait time in milliseconds of 6000 milliseconds/1000 equals 60 seconds--maxwait=60000#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样: [Property name=Property ;] #注意:"User" and "password"Two attributes are explicitly passed, so there is no need to include them here. ConnectionProperties=useunicode=true; characterencoding=gbk# Specifies the auto-commit of the connection created by the connection pool (auto-commit) state. Defaultautocommit=true#driverdefaultSpecifies that the connection created by the connection pool is read-only (read-Only ) status. #如果没有设置该值, the "setreadonly" method will not be called. (Some drivers do not support read-only mode, such as: Informix) defaultreadonly=#driverdefaultSpecifies the transaction level (transactionisolation) of the connection created by the connection pool. #可用值为下列之一: (Details visible Javadoc. ) none,read_uncommitted, read_committed, Repeatable_read, Serializabledefaulttransactionisolation=read_uncommitted

The code is as follows:

 Public Final classJdbcutils {Private StaticString url = "Jdbc:mysql://localhost:3306/jdbc?generatesimpleparametermetadata=true"; Private StaticString user = "root"; Private StaticString password = "Yezi"; //private static DataSource myDataSource = new MyDataSource2 ();    Private StaticDataSource myDataSource =NULL; Privatejdbcutils () {}/** Static code block * Executes as the class loads, executes only once, and takes precedence over the main function.     Used to initialize a class. */    Static {        Try{class.forname ("Com.mysql.jdbc.Driver"); //myDataSource = new MyDataSource2 ();Properties prop =NewProperties (); /** Write dead in the program*/            //prop.setproperty ("Driverclassname", "Com.mysql.jdbc.Driver"); //prop.setproperty ("User", "root");InputStream is= Jdbcutils.class. getClassLoader (). getResourceAsStream ("Dbcpconfig.properties");           Prop.load (IS); myDataSource = Basicdatasourcefactory.createdatasource (prop); } Catch(Exception e) {Throw NewExceptionininitializererror (e); }     }        //returns the data source because our program only deals with DataSource and does not directly access the connection pool     Public StaticDataSource Getdatasource () {returnmyDataSource; }         Public StaticConnection getconnection ()throwsSQLException {//return drivermanager.getconnection (URL, user, password);        returnmydatasource.getconnection (); }     Public Static voidFree (ResultSet rs, Statement St, Connection conn) {//Comparison of the release mode of the standard, more trouble        Try {            if(rs! =NULL) Rs.close (); } Catch(SQLException e) {e.printstacktrace (); } finally {            Try {                if(St! =NULL) St.close (); } Catch(SQLException e) {e.printstacktrace (); } finally {                if(Conn! =NULL)                    Try {                        /*the Close () method is equivalent to placing the connection in the connection pool * i.e. calling close () is equivalent to calling Mydatasource.free (conn); */Conn.close (); //Mydatasource.free (conn);}Catch(Exception e) {e.printstacktrace (); }            }        }    }}

In our previous example, our myDataSource can implement the DataSource interface, implement the Getconnection () method inside, we want to use DBCP time, the data source implementation to DBCP on the line, Because this component also implements the DataSource interface, this is the benefit of interface-oriented programming, which can be replaced by different implementations without changing our other code.

extracting a modified method from a DAO into an abstract parent class

When you're writing a program, it's necessary to encapsulate it if you find that your code is always duplicated. A section of the code changes in the extraction of the parent class, the parameters to pass the past, and then in the implementation of the class directly super call the parent class method is OK, remember to pass the parameters in the past. Overloads of multiple methods can be raised outward, but the real code implementation is only one copy.

The code will not be mentioned, the following will be posted.

using template method Design patterns to process query methods in DAO

JDBC Fourth time Learning

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.