JDBC database connectivity (II)

In order to operate the database programming language, it is necessary to establish a connection to the database.

Step JDBC connections as follows:

  • Importing JDBC package: using the Java language import statement to import the required classes beginning in Java code location.

  • Sign JDBC driver: the driver will be required to achieve the JVM loaded into memory, thus satisfy the JDBC request.

  • URL database configuration: create a properly formatted address, point to the database you want to connect to.

  • Create a connection object: to call DriverManager object's getConnection () method to establish the actual database connection.

 First, import the package

mysql驱动jar:http://central.maven.org/maven2/mysql/mysql-connector-java/

oracle驱动jar:https://www.oracle.com/database/technologies/appdev/jdbc-downloads.html

To use the standard JDBC package java.sql. *.

Second, the registered JDBC drivers

Before using the program, you must first register the driver. 

Registration driver is to load the database driver class files to process in memory.

Only once in the program can be registered. You can register the driver in one of two ways.

1. Class.forName ()
  method is recommended because it can be configured for the driver to register and portable.

Class.forName("oracle.jdbc.driver.OracleDriver"); //oracle
Class.forName("com.mysql.jdbc.Driver"); //mysql

2. DriverManager.registerDriver ()
  using the static DriverManager.registerDriver () method to register the driver.
  If a non-compatible JDK using the JVM (such as provided by Microsoft), use the registerDriver () method.

Driver myDriver = new oracle.jdbc.driver.OracleDriver(); //oracle
Driver myDriver = new com.mysql.jdbc.Driver();  //mysql
DriverManager.registerDriver( myDriver );

Third, the database URL

After loading the driver can use the DriverManager.getConnection () method to establish a connection.

Three overloaded the DriverManager.getConnection () Method:

Where each format requires a database URL. Database URL is pointing to the address database.

(1) MySQL
  JDBC driver name: com.mysql.jdbc.Driver
  the URL of the format: jdbc: mysql: // hostname / databaseName

(2) the Oracle
  JDBC driver name: oracle.jdbc.driver.OracleDriver
  the URL of the format: jdbc: oracle: thin: @hostname : portNumber: databaseName

(3) PostgreSQL
  JDBC driver name: org.postgresql.Driver
  the URL of the format: jdbc: postgresql: // hostname: port / dbname

(4) the DB2
  JDBC driver name: COM.ibm.db2.jdbc.net.DB2Driver
  the URL of the format: jdbc: db2: hostname: port Number / databaseName

(5) Sybase
  JDBC driver name: com.sybase.jdbc.SybDriver
  the URL of the format: jdbc: sybase: Tds: hostname : portNumber / databaseName

Fourth, create a connection object

DriverManager.getConnection();

 

Guess you like

Origin www.cnblogs.com/myitnews/p/11841131.html