通常,JDBC应用程序使用以下两个类之一连接到数据源。
- DriverManager:这个完全实现的类将应用程序连接到数据源,数据源由数据库URL指定。当此类首次尝试建立连接时,它会自动加载在类加载路径的任何JDBC 4.0驱动程序。请注意,应用程序必须在4.0之前手动加载任何JDBC驱动程序。
- DataSource:此接口优于DriverManager选择,因为它允许基础数据的详细信息对应用程序透明。DataSource对象的属性可以被设定,这样使得它代表一个特定的数据源。
使用DriverManager类
public Connection getConnection() throws SQLException { Connection conn = null; Properties connectionProps = new Properties(); connectionProps.put("user", this.userName); connectionProps.put("password", this.password); if (this.dbms.equals("mysql")) { conn = DriverManager.getConnection( "jdbc:" + this.dbms + "://" + this.serverName + ":" + this.portNumber + "/", connectionProps); } else if (this.dbms.equals("derby")) { conn = DriverManager.getConnection( "jdbc:" + this.dbms + ":" + this.dbName + ";create=true", connectionProps); } System.out.println("Connected to database"); return conn; }
使用DriverManager.getConnection()方法建立数据库连接。此方法需要一个数据库URL参数,而数据库URL取决于使用的DBMS。另外还有访问DBMS所需的用户名和密码作为该方法的参数。
指定数据库连接URL
posted on
浙公网安备 33010602011771号