JDBC advanced application 1

Source: Internet
Author: User
Tags finally block
About database connections

If we talk about JDBC advanced applications, it doesn't mean that they have a high technical level (maybe there is no "technical level" on the Java platform ).
Because Java is intended for users rather than for some people). It is an advanced application because it is a basic JDBC application.
The extension can optimize the performance of your application or facilitate the implementation of the application. Therefore, it is an advanced application, not an advanced application.
Technology.

In JDBC, the Java. SQL package is basic and core function, while the javax. SQL package is advanced and extended.
For the convenience of communication, we divide them into core APIs and optional APIs.

However, there are still some core API functions. I will summarize them into advanced applications, such as calling stored procedures and multiple result sets.
The reason why I want to explain these things is that you cannot find any detailed documents and routines on the Internet.
More than 95% of developers do not know how to deal with these tasks, so I will write this section in detail after returning to Shanghai.
Now let's take a look at the benefits of optional API:

We have learned that it takes the following steps to execute an SQL statement:
1. connction
2. Statement
3.statement.exe cutexxxxx ();
4. Optional processing of result sets
5. Disable necessary connction. (remind me again if you want to become a programmer at or above the intermediate level.
The statement is written in the Finally block. After the following introduction, I will introduce a method to verify whether your program has links.
Leakage)

In this case, generating a connction object is the most important task and resource-consuming, because the linked object must drive the underlying layer.
The physical connection is called to communicate with the database, so generating, closing, and then generating this link object is equivalent
The 1980s S (do you not know about the origins after the 1980 s ?) It's the same as drinking a can. You know that buying a bottle of drink is a second Cent.
The connection value is a fraction of eight points, and the money you drink is only a fraction of two points. This is the truth of a beverage factory there.
Data.
Before the javax. SQL package comes out, we can only buy this kind of drink unless you don't drink it. Some people are not convinced that they are born.
The consumer quickly discovered that it only sold the sold cans to us, because it still
The original packaging materials are used for production. The poolman connection pool is basically getconnection from drivermanager.
If the real efficiency is not your psychological function, it may be lower than a single link !!! As well as some "masterpiece" of jianghu haohan ",
No one can jump out of this box. I was also fascinated by studying these "connection pools" at that time, because anyone can take others' original codes
After reading it, I wrote a better one with the advantages of others. However, as you can see, I wrote a useful upload, download,
Htmlutil, encoder, decoder, and other tools. However, I did not write a successful connection pool .......

Let's take a further look at why the links generated by drivermanager and their connection pools cannot really improve performance.
In drivermanager objects, the vast majority of JDBC encapsulates a physical connection, that is, it captures
Socket. When you use drivermanager. getconnection (), there is a socket connected to the database to occupy you.
In addition, this method is synchronous. We all know that such physical connections are limited for any system, such as a web server.
The maximum concurrency is between 150 and 250. This is also the case for the database server. Not only do you have to consider that your program cannot use up connections, but also
Consider using these physical connections with you at the same time in different runtimes or other applications. If a server has a Java
Web server, there is a C application also accesses the database, you can not be so rude to ask people C programmers his program must
You can access the database only when your Java calls are idle. Therefore, physical connections are extremely valuable.
The Connection Pool Based on drivermanager. getconnection () is only a physical connection that is generated in advance.
Pool, and then the number will wait for you to call. It skips the time when such a link is generated. Note that the link you get is not released before,
It cannot handle other work, because the connection handle is in the user's hands. In addition, this connection pool is initialized by the program caller,
Initialization is required for each call, and whether the caller runs it in an optimized way depends on everyone's programming water.
Flat. On the other hand, if this connection pool is used for Web Container Management, it is simply garbage, because it forces the use of static variables
The container cannot implement access control at all, and it cannot be called in different runtimes.

The implementation of javax. SQL uses a buffer intermediate layer between the user link and the physical link, although it only produces
30 physical connections, but the user cannot access it. datasource returns a Java Abstract object to the user.
The datasource uniformly schedules physical connections to process the connection request back to the buffer, so that the maximum program can use valuable physical connections.
Maybe the current 30 physical connections are still not load-effective, you still need to modify the actual number of connections, but we know that our current connection
The connection method is no longer comparable to drivermanager. getconnection (). That is to say, under the same number of physical connections,
Datasource can give us more (more) Call opportunities. In fact, under normal circumstances, the next step is from drivermanager.
Getconnection () only generates a few percent of the load of the physical connection, because your call captures its handle and cannot
It works well. In addition, the programmer can only return it but cannot close it, because once the link object in the traditional connection pool is closed by the user,
The new link is created again, so the user can only release the link object,
Programming with different codes is a kind of pain. Once you do not pay attention to it, it is not a release but a close after processing the data. This error
Who is at fault ?????????????

I mentioned above that the vast majority of Java. SQL implementations are achieved by physical connections, and there are exceptions, but not those previous connection pools,
Ose is the Oracle servlet environment. It implements the servlet server in the address space of the database, and the servlet service calls
Databases do not use traditional connections because data is "Open", which is like accessing other computer files and accessing through the network.
Differences between local files. Although it also provides a standard JDBC interface for you to call, it is not encapsulated with JDBC at the underlying layer.

Another advantage of datasource is that it completely isolates databases from applications, and how to configure Server generation
Datasource references have nothing to do with program development. In program development, you only need to use jdni to find the logical name of datasource.
In drivermanager. getconnection (), you have to write the database driver name, access address, user, and password in your
In an application, even if you can read these attribute strings from the configuration file, you must modify the paths of Different server configuration files.
Datasource provides standard configuration.

To put it bluntly, how can we use datasource to connect to a database?

Very simple:

Datasource DS = (datasource) New initialcontext (). Lookup ("JDBC/mydb ");
Connection conn = Ds. getconnection ();

Of course, I want to show that it intentionally ignores its exceptions. in actual application, You should catch its exceptions.

If you still don't understand what jdni is, I suggest you look for some information in this area first. This can be from the aspect of WEB programming.
Basic protocols.

About datasource DS = (datasource) New initialcontext (). Lookup ("JDBC/mydb ");
Note that you only need to configure your servers (tomcat, resin, WebLogic ).
You don't understand it very well. You just need to change the example to a few words. In a while, you will gradually understand what they represent.
Then, when you call the new initialcontext (). Lookup ("JDBC/mydb") container in the container environment,
The datasource object is called for you. This process is transparent to users.
The smart friend over there has already asked, because the datasource attribute is already configured in the container, then I
In a container environment, for example, an independent application, how can I get the datasource?
In fact, if you know which default configurations are called by the container during New initialcontext (), you can
These configuration parameters are manually added without relying on the container environment. Fortunately, initialcontext can getenvironment (),
You can get this object and write down these parameters. Then, put them in an environment without these parameters.
Here are a few more words to talk about the learning method. I have hosted several forums in China (not many, two or three) and have never asked anyone
The Java technology is not invented by me. It is impossible for me to understand everything. First, the question seems to be detrimental to the "master" style (haha, actually
A real expert will ask others, and only fake masters like me will not ask others). On the other hand, I don't have to ask others, such
As in the application, What should I put to the datasource of different manufacturers? First, go to their website to view information, although
My English level is only 10% of that of everyone, but I may have more times to access an English website than you. Second, check whether there is any API shared.
We can get it. Fortunately, we can getenvironment (), but what if there is no such method? This depends on your learning attitude. Someone will discuss this forum.
The name is "high-handed", what else "Urgent, online waiting" or something. I will decompile new initialcontext () to see it.
What does it call (Confucius said, for the purpose of learning, The Decompilation is allowed, or even great, bright, and correct thinking, there are
Moral, out of low-level interests, and beneficial to the people !!! ---- Confucius quotations supplements page 1, 123rd, 4th)
If an object requires parameters during construction and there is another overload constructor without parameters, you can think about it
The default parameters are called in the parameter constructor. All you need to do is print them out. How many people do this?

Other extended functions of JDBC optional API:
Javax. SQL not only improves the performance, but also supports distributed transactions. In the traditional connection process, we
You can set setautocommit () to fasle during a link process, and then roll back and submit tasks through rollback () or commit ().
Transaction in a link process is called a local transaction, but if you want to operate on multiple databases in a transaction
If the servlet is involved in the operation, distributed transactions must be used.

I will introduce the JDBC transactions below. A celebrated feature is provided, that is, the transaction retention point has
Implemented in jdbc3.0. Previously, if we put the transaction atoms A, B, and C in a transaction, if a and B run, c fails, we can only
I have rolled back both A and B, but now we can save a and B As a vertex, and then use this vertex as a rollback or commit. This is like using Word
When writing an article, we can save a copy at different times, instead of having no more words or the current editing status.

Now we can optimize the bean we implement in our basic knowledge. Today, at home, we cannot go to the Forum. The link we wrote last time
I forgot my name. Now let's call it pooleddb.
At that time, we had split the bean into three parts to separate the generated link, while the business method and Expansion
This is the benefit of inheritance :)

Package com. inmsg. beans;

Import javax. Naming .*;
Import javax. SQL .*;

Public class pooleddb {
 
Connection con = NULL;
Private string source = "";
Public pooleddb () throws exception {// default constructor. If no parameter is added during the constructor, connect to JDBC/office.
Source = "Java: COMP/ENV/jdbc/office ";
Context Ct = new initialcontext ();
Datasource DS = (datasource) CT. Lookup (source );
Con = Ds. getconnection ();
}

// Add the overload method to link other data sources.
Public pooleddb (string source) throws exception {
This. Source = source;
Context Ct = new initialcontext ();
Datasource DS = (datasource) CT. Lookup (source );
Con = Ds. getconnection ();
}
// Be sure to assign source to the member variable this. Source first, because there is a makeconnection ()
// Auxiliary method. If source is not assigned to this. Source, makeconnection () calls the default source string.

Private void makeconnection () throws exception {
Context Ct = new initialcontext ();
Datasource DS = (datasource) CT. Lookup (source );
Con = Ds. getconnection ();
}

// Now we take the close () method to the parent class for implementation. This is a comprehensive consideration. It is a business method, no matter what
// Method to obtain the link. It will not be modified, but why is it encapsulated in the parent class? In this way, you can use an independent parent class.
// Perform a link test. If I only want to try whether the database can be connected, I don't have to reference the subclass. Just use this parent class.
Public void close () throws exception {
If (con! = NULL &&! Con. isclosed () con. Close ();
}
}

In general, the constructor tries its best to capture Exception Handling instead of throwing exceptions. However, as bean implementation, it is not easy to catch exceptions by callers.
When the exception information is displayed, It is thrown to the caller for processing. In addition, this class must be called in the application, and it must be considered as a bean call.
There must be a constructor without parameters, otherwise it cannot be called as a JavaBean. The exception is thrown to the caller for another purpose. I designed this
In this case, you must use try {} catch () {} block, so that you will think of adding a finally {}.
Call the bean or encapsulation class linked to your database in the following form:
Pooleddb Pd = NULL;
Try {
Pd = new pooleddb ();
....................
}
Catch (exception e ){}
Finally {try {PD. Close ();} catch (exception ex ){}}

If you want to test whether your database connection has been leaked, set the maximum number of connections in datasource to 1 and use only one link.
In this case, if no link is closed in your program, the following program cannot be accessed, and then test your program from start to end. Once
If you find that you cannot access the database, you can view the accessed code. After testing all the programs, you can rest assured. Generally, I don't need to do this.
Test, because when I write a database connection, close is written if no object is generated:

Pooleddb Pd = NULL;
Try {}
Catch (exception e ){}
Finally {try {PD. Close ();} catch (exception ex ){}}
Then press enter in the curly braces of try {} to add Pd = pooleddb (); and the Business Code :) of course, you are smarter than me.
In this way, you will not forget to close.
Don't be so happy. You still haven't got the best solution so far. We will link the following to this database:
Bean (class) constantly optimized ..................................

Well, let's talk about the javax. SQL Link first. Today is Saturday. I went out for a while (there are no beautiful girls on the streets of Guangzhou !)

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.