Java--JDBC learning--Get database links

Source: Internet
Author: User
Tags driver manager prepare

Data persistence

Persistence (persistence):

    • Save the data to an off-the-shelf storage device for later use. In most cases, especially for enterprise applications, data persistence means that the data in-memory is saved to the hard disk to be "cured", and the implementation of the persistence process is mostly done through a variety of relational databases.
    • The primary application of persistence is to store in-memory data in a relational database and, of course, in disk files and XML data files.
Data storage technology in Java

In Java, database access technology can be divided into the following categories:

    1. JDBC Direct access to the database
    2. JDO Technology third-party O/R tools such as Hibernate, Ibatis, etc.

JDBC is the cornerstone of Java's access to the database, JDO, hibernate, etc. just better encapsulate JDBC.

JDBC Foundation

JDBC (Java database Connectivity) is a common interface (a set of APIs) that is independent of a particular database management system, a common SQL database access and operation, and defines a standard Java class library to access the database, which can be used in a standard way, Easy access to database resources

JDBC provides a unified way to access different databases, shielding developers from some of the details.

The goal of JDBC is to enable Java programmers to use JDBC to connect to any database system that provides a JDBC driver, which simplifies and accelerates the development process by eliminating the need for the programmer to have an excessive understanding of the characteristics of a particular database system.

JDBC Architecture

The JDBC Interface (API) consists of two levels:

Application-oriented Api:java API, an abstraction interface for application developers to use (connect databases, execute SQL statements, and get results).

Database-oriented Api:java Driver API for developers to develop database drivers.

JDBC Driver classification

JDBC Driver: A class library of JDBC implementation classes made by each database vendor based on the specifications of the JDBC

There are four types of JDBC drivers:

First Category: Jdbc-odbc Bridge.

Second class: Part of the local API part of the Java driver.

Class III: JDBC Network pure Java driver.

Class Fourth: Pure Java drivers for local protocols.

The third to fourth two classes are pure Java drivers,

As a result, for Java developers, they have advantages in terms of performance, portability, functionality, and so on.

Odbc

Early access to the database was a proprietary API that was called by the database vendor. In order to provide unified access under the Windows platform, Microsoft introduced the ODBC (Open database Connectivity), and provided the ODBC API, the user only needs to call the ODBC API in the program, the ODBC driver will The call transformation becomes a call request to a particular database.

An ODBC-based application operates on a database without relying on any DBMS (the Database manager system), does not interact directly with the DBMS, and all database operations are done by the corresponding DBMS's ODBC driver. That is, either FoxPro, Access, MySQL, or Oracle databases are accessible using the ODBC API. Thus, the greatest advantage of ODBC is the ability to handle all databases in a unified manner.

JDBC-ODBC Bridge

The Jdbc-odbc bridge itself is also a driver, and with this drive, you can access the database using JDBC-API through ODBC. This mechanism actually translates the standard JDBC calls into the corresponding ODBC calls and accesses the database through ODBC.

Because multiple calls are required, it is inefficient to access the database using the Jdbc-odbc bridge.

In the JDK, the implementation class (Sun.jdbc.odbc.JdbcOdbcDriver) of the Jdbc-odbc Bridge is provided.

Part of the local API part Java driver
    1. This type of JDBC driver is written in Java and calls the local API provided by the database vendor.
    2. Accessing the database through this type of JDBC driver reduces the call link of ODBC and improves the efficiency of database access.
    3. In this way, the local JDBC driver and the vendor-specific local APIs need to be installed on the customer's machine.

JDBC Network Pure Java Driver

This driver uses the middleware application server to access the database. The application server acts as a gateway to multiple databases through which the client can connect to different database servers.

The application server usually has its own network protocol, and the Java user program sends the JDBC call to the application server through the JDBC driver, and the application server uses the local program driver to access the database to complete the request.

Pure Java driver for local protocol

Most database vendors have supported network protocols that allow client programs to communicate directly with the database over the network.

This type of driver is written entirely in Java, using a Socket connection to the database to convert the JDBC call to a direct-attached network call with the vendor-specific network protocol.

JDBC API

The JDBC API is a series of interfaces that enable an application to join a database, execute an SQL statement, and get the results returned.

Driver interface

The Java.sql.Driver interface is the interface that all JDBC drivers need to implement.

    1. This interface is provided to the database vendor, and different database vendors provide different implementations.
    2. Instead of directly accessing the class that implements the Driver interface in the program, the Driver Manager class (Java.sql.DriverManager) calls these Driver implementations.
Loading and registering the JDBC driver
    1. Loading the JDBC driver calls the class's static method, forname (), passing it the JDBC driver's name to be loaded.
    2. The DriverManager class is the driver manager class that is responsible for managing drivers.
    3. You typically do not have to explicitly call the Registerdriver () method of the DriverManager class to register an instance of a driver class, because the driver class for the Driver interface contains a static block of code that, in this static code block, calls Drivermanager.registerdriver () method to register an instance of itself.
Establish a connection

You can call the Getconnection () method of the DriverManager class to establish a connection to the database.

The JDBC URL is used to identify a registered driver, and the driver manager chooses the correct driver through this URL to establish a connection to the database.

The standard for a JDBC URL consists of three parts, separated by colons.

jdbc:< Sub-Protocol >:< sub-name >

    1. Protocol: The protocol in the JDBC URL is always jdbc
    2. Sub-Protocol: a sub-protocol used to identify a database driver
    3. Sub-name: A way to identify a database. Sub-names can vary depending on the sub-Protocol, and the purpose of the sub-name is to provide sufficient information to locate the database.
JDBC URLs for several common databases

    1. For Oracle database connections, take the following form: Jdbc:oracle:thin: @localhost: 1521:sid.
    2. For SQL Server database connection, take the following form: jdbc:microsoft:sqlserver//localhost:1433; Databasename=sid.
    3. For MYSQL database connection, take the following form: Jdbc:mysql://localhost:3306/sid.

Examples illustrate several ways to connect to a database:

Preparatory work:

1. Join the MySQL Driver
1). Unzip the Mysql-connector-java-5.1.7.zip
2). Create a new Lib directory under current project
3). Copy the Mysql-connector-java-5.1.7-bin.jar to the Lib directory
4). Right-Build-path, add to BuildPath is added to the classpath. S

Jdbc.properties file
#driver =oracle.jdbc.driver.oracledriver#jdbcurl=jdbc:oracle:thin: @localhost: 1521: Orcl#user= Scott#password=javadriver=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://  Localhost:3306/soyoungboyuser=rootpassword=1230

Mode 1:

DriverManager is a managed class of drivers.
1). The database connection can be obtained through the overloaded getconnection () method. More Convenient
2). Multiple drivers can be managed at the same time: If multiple database connections are registered, call getconnection ()
method, a different database connection is returned when the parameter passed in is different.

 PublicConnection GetConnection2 ()throwsexception{//1. Prepare 4 strings to connect to the database. //1). Create a Properties objectProperties Properties =NewProperties (); //2). Gets the input stream corresponding to the Jdbc.propertiesInputStream in = This. GetClass (). getClassLoader (). getResourceAsStream ("Jdbc.properties"); //3). Load 2) corresponding input streamproperties.load (in); //4). Specifically determine the user, password, etc. 4 strings. String user = Properties.getproperty ("User"); String Password= Properties.getproperty ("Password"); String Jdbcurl= Properties.getproperty ("Jdbcurl"); String Driver= Properties.getproperty ("Driver"); //2. Load the database driver (the corresponding Driver implementation class has a registered-driven static code block.)Class.forName (driver); //3. Get the database connection through the DriverManager getconnection () method.        returndrivermanager.getconnection (jdbcurl, user, password); }

Way two:

 Public voidTestdrivermanager ()throwsexception{//1. Prepare 4 strings to connect to the database. //the full class name of the drive.String Driverclass = "Com.mysql.jdbc.Driver"; //JDBC URLString Jdbcurl = "Jdbc:mysql:///test"; //UserString user = "root"; //PasswordString password = "1230"; //2. Load the database driver (the corresponding Driver implementation class has a registered-driven static code block.)Class.forName (Driverclass); //3. Get the database connection through the DriverManager getconnection () method.Connection Connection =drivermanager.getconnection (jdbcurl, user, password);             System.out.println (connection); }

Way three:

 Public voidTestdriver ()throwsSQLException {//1. Create an object of the Driver implementation classDriver Driver =NewCom.mysql.jdbc.Driver (); //2. Basic information about preparing a connection database: URL, user, passwordString url = "Jdbc:mysql://localhost:3306/test"; Properties Info=NewProperties (); Info.put ("User", "root"); Info.put ("Password", "1230"); //3. Call the Connect (URL, info) of the Driver interface to get the database connectionConnection Connection =driver.connect (URL, info);    System.out.println (connection); }

Mode four: Write a common method, without modifying the source program, you can get the connection of any database

Solution: The full class name, URL, user, and password of the database-driven Driver implementation class are put into a configuration file, which is implemented by modifying the configuration file and decoupling the specific database.

*/ PublicConnection getconnection ()throwsexception{String Driverclass=NULL; String Jdbcurl=NULL; String User=NULL; String Password=NULL; //read the Jdbc.properties file under the ClasspathInputStream in =getclass (). getClassLoader (). getResourceAsStream ("Jdbc.properties"); Properties Properties=NewProperties ();        Properties.load (in); Driverclass= Properties.getproperty ("Driver"); Jdbcurl= Properties.getproperty ("Jdbcurl"); User= Properties.getproperty ("User"); Password= Properties.getproperty ("Password"); //by reflecting common Driver objects.Driver Driver =(Driver) class.forname (Driverclass). newinstance (); Properties Info=NewProperties (); Info.put ("User", user); Info.put ("Password", password); //get the database connection through the Driver Connect method.Connection Connection =Driver.connect (Jdbcurl, info); returnconnection; }

Java--JDBC learning--Get database links

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.