English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Después de instalar el driver correspondiente, puede usar JDBC para establecer una conexión con la base de datos.
La programación involucrada en la creación de conexiones JDBC es muy simple. Estos son los cuatro pasos simples-
Importar el paquete JDBC:Agregar una declaración en el programa Java importpara importar las clases necesarias en el código Java.
Registrar el driver JDBC: Este paso hace que el JVM cargue la implementación del driver necesaria en la memoria, lo que permite satisfacer sus solicitudes JDBC.
Configuración de la URL de la base de datos: Esto es para crear una dirección bien formada que apunte a la base de datos a la que desea conectarse.
Establecer el objeto de conexión:Finalmente, escribirDriverManagerObjetogetConnection()方法的调用的代码,以建立实际的数据库连接。
Import 语句告诉 Java 编译器在哪里可以找到代码中引用的类,并且放在源代码的开头。
要使用标准 JDBC 包(它允许您选择、插入、更新和删除 SQL 表中的数据),请将以下导入添加到源代码中
import java.sql.* ; // 用于标准JDBC程序 import java.math.* ; // 获得BigDecimal和BigInteger支持
在使用驱动程序之前,必须在程序中注册该驱动程序。注册驱动程序是将 Oracle 驱动程序的类文件加载到内存中的过程,因此可以将其用作 JDBC 接口的实现。
你只需要在你的程序中注册一次。您可以通过以下两种方式之一注册驱动程序。
注册驱动程序的最常见方法是使用Java的 Class.forName() 方法,将驱动程序的类文件动态加载到内存中,内存会自动进行注册。此方法是可取的,因为它使您可以使驱动程序注册成为可配置和可移植的。
以下示例 Class.forName( ) 用于注册Oracle驱动程序
try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(ClassNotFoundException ex) { System.out.println("Error: unable to load driver class!"); System.exit(1); }
您可以使用getInstance()方法来解决不兼容的JVM,但是随后您必须编写两个额外的Exception的代码,如下所示:
try { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); } catch(ClassNotFoundException ex) { System.out.println("错误:无法加载驱动程序类!"); System.exit(1); catch(IllegalAccessException ex) { System.out.println("错误:加载时出现访问问题!"); System.exit(2); catch(InstantiationException ex) { System.out.println("错误:无法实例化驱动程序!"); System.exit(3); }
您可以用来注册驱动程序的第二种方法是使用静态方法 DriverManager.registerDriver() .
如果使用的是不兼容JDK的JVM(例如Microsoft提供的JVM),则应使用 registerDriver() 方法。
以下示例用于registerDriver()注册Oracle驱动程序-
try { Driver myDriver = new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver(myDriver); } catch(ClassNotFoundException ex) { System.out.println("Error: unable to load driver class!"); System.exit(1); }
加载驱动程序之后,可以使用 DriverManager.getConnection ()方法建立连接。为了便于参考,让我列出 DriverManager.getConnection() 三种重载方法
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
在这里,每种形式都需要一个数据库URL。数据库URL是指向您的数据库的地址。
制定数据库URL是与建立连接相关的大多数问题发生的地方。
下表列出了常用的JDBC驱动程序名称和数据库URL。
数据库 | JDBC驱动程序名称 | URL格式 |
---|---|---|
MySQL | com.mysql.jdbc.Driver | jdbc:mysql://hostname/ databaseName |
ORACLE | oracle.jdbc.driver.OracleDriver | jdbc:oracle:thin:@hostname:port Number:databaseName |
DB2 | COM.ibm.db2.jdbc.net.DB2Driver | jdbc:db2:hostname:port Number/databaseName |
Sybase | com.sybase.jdbc.SybDriver | jdbc:sybase:Tds:hostname: port Number/databaseName |
URL格式中所有突出显示的部分都是静态的,您只需要根据数据库设置更改其余部分。
我们列出了三种 DriverManager.getConnection() The method to create a connection object.
The most commonly used form of getConnection() requires you to pass the database URL,usernameandpassword
Assuming you are using Oracle'sthinThe driver will specify the host:port:databaseName value for the database part of the URL.
If you are on TCP / IP address192.0.0.1and your Oracle listener is configured to listen on port1521and your database name is EMP, then the complete database URL will be-
jdbc:oracle:thin:@amrood:1521:EMP
Now, you must call the method getConnection() with the correct username and password to getConnectionObject, as follows:
String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; String USER = "username"; String PASS = "password" Connection conn = DriverManager.getConnection(URL, USER, PASS);
The second form of DriverManager.getConnection() method only requires a database URL-
DriverManager.getConnection(String url);
However, in this case, the database URL contains the username and password and has the following conventional form-
jdbc:oracle:driver:username/password@database
Therefore, the above connection can be created as follows-
String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP"; Connection conn = DriverManager.getConnection(URL);
The third form of DriverManager.getConnection() method requires a database URL and a Properties object-
DriverManager.getConnection(String url, Properties info);
The property object contains a set of keywords-Value pair. It is used to pass driver properties to the driver during the call to getConnection() method.
Para establecer la conexión igual que en el ejemplo anterior, utilice el siguiente código-
import java.util.*; String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; Properties info = new Properties(); info.put("user", "username"); info.put("password", "password"); Connection conn = DriverManager.getConnection(URL, info);
Al final del programa JDBC, se requiere cerrar explícitamente todas las conexiones con la base de datos para finalizar cada sesión de base de datos. Pero si lo olvida, el recolector de basura de Java cerrará la conexión cuando limpie los objetos antiguos.
Depender del recolector de basura, especialmente en programación de bases de datos, es una mala práctica de programación. Debe acostumbrarse a cerrar siempre la conexión de base de datos utilizando el método close() asociado con el objeto de conexión.
Para asegurarse de cerrar la conexión, puede proporcionar un bloque "finally" en el código.finallyEl bloque siempre se ejecuta, sin importar si ocurre o no una excepción.
Para cerrar la conexión abierta anterior, debe llamar al método close() de la siguiente manera:
conn.close();
Cerrar explícitamente la conexión puede ahorrar recursos del DBMS, lo que satisfará a su administrador de bases de datos.
Para entender mejor, le recomendamos que aprendaJDBC-Tutorial de código de ejemplo.