20155335 Eucun 2016-2017-2 "Java Programming" Nineth Week study Summary

Source: Internet
Author: User
Tags driver database hosting sql using

Study number 2016-2017-2 "Java program design" Nineth Week Learning Summary

# #JDBC入门

Before formally introducing JDBC, it is known that JDBC is the solution to execute SQL, and developers use the standard interface of JDBC, where developers do not have to touch the differences of the underlying database drivers.

In this chapter, we need to understand the use and concepts of JDBC and API, we first understand how the application communicates with the database, the database itself is a self-running application Cheng, the programmer writes the application uses the communication protocol to the database to carry on the instruction exchange, carries on the data the deletion and the discovery.

Typically, the application uses a set of linked libraries that specifically communicate with the database to simplify the process of writing to the database, and we should be aware of how the application calls this set of link libraries. Different databases often have different communication protocols, which are used to connect libraries of different databases on the API, and the application can use the link library directly for example:

Xysqlconnection coon = new Xysqlconnection ("Localhoost", "root", "1234");

Coon.selectdb ("gossip");

Xysqlquery query = Coon.query ("SELECT * from T_user");

It may be assumed that the API in this program code is provided by a link library of an XY database vendor, which is called when the database to be used in the application is brought online, and if the application intends to use the AB vendor database and the database online API it provides, the program code will be obtained.

If another consideration: if the XY database Vendor link library is actually used with the operating system dependencies, if only to change the operating system, it is necessary to first consider whether there is a database link library to provide the platform.

Not without the need to replace the database, application cross-platform is also a common requirement, JDBC is basically to solve these problems, JDBC is the standard specification of Java database, in particular, define a set of standard classes and interfaces, the application needs to connect to the database when the standard API calls, The interface of the standard API is operated by the data vendor, often referred to as the JDBC driver.

A communication protocol is established between the known database and the JDBC driver, the JDBC driver is placed at the lowest level, the JDBC standard API is placed on it, and the JDBC standard is divided into two parts: the JDBC Application developer interface and the JDBC driver developer interface, if the application requires an online database, is to call the JDBC Application developer interface, the API is mainly in JAVA.SQ1 and javax.sq1 two packages, the JDBC driver developer interface is the database vendor operation driver Specification.

If you want to switch to an Oracle database in the future, just replace the Oracle driver, specifically the jar document that was classpath to the Oracle driver, but the application does not have to be modified in this province.

Replace the driver without modifying the application

When you operate a JDBC application, there are four types of driver-driven programs

(1) Type1:jdbc-odbc Bridge Driver

ODBC is a Microsoft-led database connectivity standard, and basically JDBC is a reference to ODBC development. Therefore, ODBC is the most mature on Microsoft systems.

The Type1 driver translates the JDBC call into a call to the ODBC driver, which is operated by the ODBC driver database such as

Because of the ready-made ODBC architecture, you simply need to convert the JDBC call to an ODBC call, so it is very easy to manipulate the driver. The driver is included with the ORACLE/SUNJDK, and the package name begins with Sun.jdbc.odbc.

However, JDBC and ODBC are not one-to-one correspondence, so partial calls cannot be converted directly, and access speed is limited due to multi-layer conversion calls. ODBC itself needs to be set up on the platform first.

(2) type2:native API Driver

This type of driver will call the native link library provided by the database in its native way, and the JDBC method call will be converted to the related API call in the native link library, because the native link library is used, so the driver itself is dependent on the platform. One of the goals of the JDBC driver is not reached: cross-platform but because the database native API is called directly, there is a chance to become the fastest driver in 4 types in speed.

The Type2 driver has the opportunity to become the fastest driver, the advantage of speed is to obtain the database corresponding data, the creation of relevant JDBC API operation object, but the driver itself can not cross the platform, before use must first on the platform for the driver installation settings.

(3) Type3:jdbc-net Driver

This type of JDBC driver transforms a JDBC method call into a specific network protocol (PROTOCOL) call, which is intended to be a remote protocol operation with a database-specific mediation server or component, while a mediation server or component is actually operating with the database.

(4) type4:native Protocol Driver

This type of driver operation is typically provided directly by the database vendor, which translates the JDBC call into a database-specific network protocol and communicates with the database

Because this type of driver has the primary role of translating JDBC calls into specific network protocols, drivers can be implemented using purely Java technology, so this type of driver can be used across platforms, and no longer needs to be type3 for architectural resiliency, such as this type of driver. Is the most common type of drive.

In order to connect the database system, must have the vendor operation JDBC Driver, must set the driver's jar document in the classpath, but if uses idea, the program project will have the way which manages classpath, usually is the new jar and so on the command. For example, NetBeans can add a link library like this:

(1) Right-click on the Libraries node on the project and choose the Add Jar/folder command from the popup shortcut menu

(2) In the Add Jar/folder dialog box that appears, select the driver JAR document after the stand-alone button is opened.

(3) Confirm that the jar document appears on the Libraries node of the project, which indicates that the jar document is in the management of the classpath in the project.

Basic database operations related to the JDBC interface or class in the java.sql package, to go to the database online, there must be three actions

    1. Registering the Driver Action object

The object that operates the driver interface is the starting point for JDBC to access the database, and basically, must call Regisiterdriver () to register

Just try to load the. Class document of the driver interface operation class and you will complete the registration:

Drivermanager.regisiterdriver (New Com.mysql.jdbc.Driver ());

However, in fact seldom write the program code this action, as long as the way to load the driver interface operation of the class. Class document, the registration will be completed.

If you view MySQL's driver class operation source code

You can see that the driver instance is registered in the static block, and the static block is loaded into the. Class document. With JDBC, there are 4 ways to load. Class documents

(1) using Class.forName ();

(2) Establish an instance of the driver interface operation class by itself.

(3) Start JVM is the specified Jdbc.drivers property

(4) Set/services/java.sql.driver document in Jar

The first way has just been explained. The second way is to write the program code directly:

Java.aql.Driver Driver = new Com.mysql.jdbc.Driver ();

    1. Get Connection Action Object

To obtain the connection operation object, it can be obtained through the DriverManager getconnection ();

Connection conn = driver.getconnection (Jdbcurl,username,password);

Also provide the JDBC URL, which defines the protocol, sub-protocol, and data source identification of the linked database:

Protocol: Sub-Protocol: Data source recognition

In addition to the protocol in the JDBC URL always starting with JDBC, the JDBC URL format is different in the database, you must query the database product name or user manual. In MySQL, for example, the sub-protocol is the bridge driver, the database product name or the online mechanism, such as using MySQL, the sub-protocol name is MySQL '. The database identifies the database address, port number, name, user, password, and other information. MySQL is written in the following ways:

JDBC:MYSQL://Host Name: Port/database name? Parameter = value & parameter = value.

SqlException is an exception object that is often encountered in processing JDBC, representing the object when an error occurs during a database operation. SqlException is an exception to be inspected, you must use Try ... Catch...finally explicitly handles attempts to close related resources when an exception occurs.

    1. Close the Connection action object

After you have obtained the connection object, you can use the isclosed () method to test whether the database link is closed. After you have finished working with the database, you must use Close () to close the link to the database and the necessary resources related to the connection, such as online related objects, authorized resources, and so on, if you are sure that you do not need a link.

The driver Connect () method returns NULL when connection cannot be obtained, so simply, Drivermanger tries to bring it online one by one using the driver instance. If the connection object is returned successfully online, if an exception occurs, DriverManager logs the first exception and continues to try the other driver (), which is not available when all driver have been tried, and if a record exception is thrown during the original attempt, No, it is also thrown exception to inform the driver that there is no suitable.

Test if the database is online and get Connecton instances:

Using statement, ResultSet

Connection is the representative object of the database connection, and then the SQL is executed. You must obtain the java.sql.Statement operand, which is the representative object of the SQL description, and you can use connection's createstatement () to establish the statement object:

Statement stmt = Conn.createstatement ();

After you have obtained the statement object, you can execute SQL using methods such as Excuteupdate (), Excutequery (), and so on. Excuteupdate () is used primarily to execute SQL that changes the contents of the database, such as Create table,insert,drop table,alter table, and a t_message table can be created in the demo database:

Use demo;

CREATE TABLE t_message{

Id INT not NULL auto_increment PRIMARY KEY,

Name CHAR (a) is not NULL,

Email CHAR;

}charset=utf8;

Statement's Excutequery () sql,executeuplate () for querying a database such as Select will return an int result representing the number of changes in the data, Excutequery () will return the Java.sql.ResultSet object, representing the query result, the query will be a sum of data, you can use ResultSet's next () to move to the next data, he will return ture or false to indicate whether 1 has the next data. Statement execute () can be used to execute SQL, and can test whether SQL is executing a query or an update, and returning ture means that SQL execution will return resultset as the result of the query. You can now use Getresultset () to get the ResultSet object. If Excute returns false, which means that SQL execution returns the number of updates or no results, you can use Getupdatecount () to get the number of updates, and you can use Excute () If you are not previously aware that SQL execution is a query or an update.

Summarize what you learned this week as simple as possible.

Try not to transcription, waste time

Read it, do not understand, learn to remember the experience

# # Problems and solutions in textbook learning

-Problem 1:xxxxxx

-Problem 1 Solution: XXXXXX

-Problem 2:xxxxxx

-Problem 2 Solution: XXXXXX

- ...

# # Problems in code debugging and resolution process

-Problem 1:xxxxxx

-Problem 1 Solution: XXXXXX

-Problem 2:xxxxxx

-Problem 2 Solution: XXXXXX

- ...

# # [Code Hosting] (Code Cloud Learning Project LINK)

Http://git.oschina.net/tianmaxingkomg/xinjianxianmu

(run result of statistics.sh script)

# # last week quiz summary of the wrong title

-Wrong question 1 and why, understand the situation

-Wrong question 2 and why, understand the situation

- ...

# # Pairs and mutual comments

# # # Scoring Standard

1. Correct use of markdown syntax (plus 1 points):

-Do not use markdown without extra points

-No extra points for grammatical errors (links cannot be opened, table is wrong, list is incorrect ...) )

-No extra points for typesetting confusion

2. Complete features in the template (plus 1 points)

-Lack of "problem in textbook learning and solution process" without extra points

-Lack of "problem in code debugging and resolution process" without extra points

-[Code Hosting] (link) cannot be opened without extra points

-Lack of "pairing and mutual evaluation" cannot be opened without extra points

-The lack of "Last week's exam error Summary" Cannot add points

-Missing "progress bar" cannot be added

-Lack of "reference material" for no extra points

-Blog comments last week

-[Study No. 1] (blog link)

-[Study No. 2] (blog link)

-[Study No. 3] (blog link)

-[Study No. 4] (blog link)

- ...

# # Other (sentiment, thinking, etc., optional)

Xxx

Xxx

# # Learning Progress bar

| | Lines of code (new/cumulative) | Blog volume (Add/accumulate) | Learning time (NEW/cumulative) | Important growth |

| --------   | :----------------:|:----------------:|:---------------:  |:-----:|

| Target |   5000 Rows | 30 Articles |       400 hours | |

| First week |   200/200 | 2/2 |       20/20 | |

| Second week |   300/500 | 2/4 |       18/38 | |

| Third week |   500/1000 | 3/7 |       22/60 | |

| Week Four |   300/1300 | 2/9 |       30/90 | |

Try to record "planned learning time" and "actual learning time" to see if you can improve your planning skills by the end of the semester. This work is very important and useful in learning.

Formula for time-consuming estimation

: y=x+x/n, y=x-x/n, the number of training, X, Y is close.

Reference: [Why is it so difficult to estimate a software engineering application] (http://www.cnblogs.com/xinz/archive/2011/04/05/2005978.html), [Software engineering estimation Method] (http:// www.cnblogs.com/xinz/archive/2011/04/06/2007294.html)

-Scheduled study time: 15 hours

-Actual learning Time: 12 hours

-Improve the situation:

(Have time to see more [Modern software engineering courseware

Software engineer Competency Self-evaluation Table] (http://www.cnblogs.com/xinz/p/3852177.html))

# # References

-[Java Learning Note (8th Edition)] (http://book.douban.com/subject/26371167/)

-[Java Learning Note (8th Edition) Learning Guide] (http://www.cnblogs.com/rocedu/p/5182332.html)

-  ...

20155335 Eucun 2016-2017-2 "Java Programming" Nineth Week study Summary

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.