- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
- public class Main {
- public static Connection getConnection(String dbURL, String user, String password)
- throws SQLException, ClassNotFoundException {
- Class.forName("com.mysql.jdbc.Driver");
- Properties props = new Properties();
- props.put("user", user);
- props.put("password", password);
- props.put("autoReconnect", "true");
- return DriverManager.getConnection(dbURL, props);
- }
- public static void main(String[] args) {
- Connection conn = null;
- try {
- conn = getConnection("jdbc:mysql://localhost/empDB", "root", "pass");
- } catch (Exception ex) {
- System.out.println("SQLException: " + ex.getMessage());
- }
- }
- }
复制代码 这也算是一种链接方式了。当然可以使用xml作为数据源,最后解析此xml文档来获取连接,相对方便灵活多变,
xml文档如:- <database id="db1">
- <vendor>sqlserver</vendor>
- <url>jdbc:microsoft:sqlserver://localhost:1433;databasename=testDB</url>
- <driver>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver>
- <username>sa</username>
- <password>sa</password>
- ...
- </database>
复制代码 剩下来的 就是解析这个xml文档里,具体的可以看看相关语言解析xml的方法 |