It is used to understand the JDBC and driver connected to the database, and to connect the database to jdbc.

Source: Internet
Author: User

It is used to understand the JDBC and driver connected to the database, and to connect the database to jdbc.
Understanding:

When a java application establishes a connection with a database, it first communicates with the driver provided by the database vendor through jdbc (jdbc is included in jdk), and then the driver communicates with the database.

Drivers provided by database vendors:

There are multiple types of databases, such as mysql and oracle. Different databases have different drivers. Before other operations, download and import the corresponding driver jar package.

Connection test procedure:

First declare the url, user name, and password of the database used (database)

        private static String url="jdbc:mysql://localhost:3306/mydb";private static String name="root";private static String password="1234";
1. Load the driver 2. Use connect to establish a connection with the database

There are two ways to load the driver:

1 public static void main (String [] args) {2 try {3 // load driver 4 Class. forName ("com. mysql. jdbc. driver "); 5 // use connect to establish a Connection with the database 6 connection Connection = (Connection) DriverManager. getConnection (url, name, password); 7 System. out. println ("database connection successful"); 8} catch (Exception e) {9 System. out. println ("database connection failed"); 10 e. printStackTrace (); 11} 12}

 

Or:

1 public static void main (String [] args) {2 try {3 // load Driver 4 driver Driver = new Driver (); 5 DriverManager. registerDriver (driver); // 6 // use connect to establish a Connection with the database 7 connection Connection = (Connection) DriverManager. getConnection (url, name, password); 8 System. out. println ("database connection successful"); 9} catch (Exception e) {10 System. out. println ("database connection failed"); 11 e. printStackTrace (); 12} 13}

Output:

Database Connection successful

 

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.