美文网首页
Java读取不同类型数据库配置文件连接数据库

Java读取不同类型数据库配置文件连接数据库

作者: 肥仔鱼爱洗澡 | 来源:发表于2019-09-29 21:16 被阅读0次

一、前言

为了方便理解,示例代码的数据库名称就叫【dbName】

127.0.0.1:1433 为数据库本地服务IP

登录数据库的用户名与密码需要根据自己的数据库登陆名与密码去更改,数据库名称也一样

以下示例可以自行封装成一个方法,也可以封装成方法后放在一个独立的类当中作为独立的数据库操作工具类,以便扩展

工程结构:

工程结构

二、变量

数据库配置直接定义为 变量

2.1 示例代码:

// ConnectTest_1.java

package dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectTest_1 {
    public static void main(String[] args) {
        // 连接对象
        Connection connection = null;
        // 数据库驱动名称
        String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        // 数据库URL
        String url = "jdbc:sqlserver://127.0.0.1:1433;" + "DatabaseName=" + "dbName";
        // 登录数据库的用户名
        String userName = "root";
        // 登陆数据库的密码
        String password = "root";
        try {
            // 加载 SQL Server 驱动程序,得到 Connection 对象
            Class.forName(driverName);
            // 建立数据库连接
            connection = DriverManager.getConnection(url, userName, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 提示语
        System.out.println("Connect successfully ! ");
        try {
            // 关闭数据库连接
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

三、properties 类型文件

3.1 前期准备:

数据库配置放在 properties 文件,文件名为 XXXX.properties,这里作为示例,文件名称为 dbConfig.properties

引入架包:sqljdbc4.jar

3.2 dbConfig.properties 文件

driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=dbName
user=root
pwd=root

3.3 示例代码:

// ConnectTest_2.java

package dbutil;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectTest_2 {
    public static void main(String[] args) {
        Properties properties = null;
        Connection connection = null;
        String driverName = null;
        String url = null;
        String userName = null;
        String password = null;
        properties = new Properties();
        try {
            // 加载配置文件
            properties.load(new FileInputStream("src/dbutil/dbConfig.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取对应的数据库配置属性
        driverName = properties.get("driver").toString();
        url = properties.get("url").toString();
        userName = properties.get("user").toString();
        password = properties.get("pwd").toString();
        try {
            // 加载 SQL Server 驱动程序,得到 Connection 对象
            Class.forName(driverName);
            // 建立数据库连接
            connection = DriverManager.getConnection(url, userName, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 提示语
        try {
            // 关闭数据库连接
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

四、xml 类型文件

4.1 前期准备

数据库配置放在 XML 文件,文件名为 XXXX.xml,这里作为示例,文件名称为 dbConfig.xml

引入架包:sqljdbc4.jar

4.2 dbConfig.xml 文件

<?xml version="1.0"?>
<sqlConfig>
    <driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver>
    <dbName>dbName</dbName>
    <url>jdbc:sqlserver://127.0.0.1:1433;DatabaseName=</url>
    <user>root</user>
    <pwd>root</pwd>
</sqlConfig>

4.3 示例代码:

// ConnectTest_3.java

package dbutil;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ConnectTest_3 {
    /**
     * @description 读取数据库配置属性
     * @return
     */
    public static HashMap<String, String> getSQLConfig() {
        HashMap<String, String> sqlConfig = new HashMap<String, String>();
        NodeList nl = null;
        Node classNode = null;
        try {
            // 创建文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File("src/dbutil/dbConfig.xml"));
            /**
             * 获取包含数据库配置的文本结点
             */
            // 数据库驱动
            nl = doc.getElementsByTagName("driver");
            classNode = nl.item(0).getFirstChild();
            sqlConfig.put("driver", classNode.getNodeValue().trim());
            // 数据库名
            nl = doc.getElementsByTagName("dbName");
            classNode = nl.item(0).getFirstChild();
            sqlConfig.put("dbName", classNode.getNodeValue().trim());
            // 本地URL
            nl = doc.getElementsByTagName("url");
            classNode = nl.item(0).getFirstChild();
            sqlConfig.put("url", classNode.getNodeValue().trim());
            // 数据库登录名
            nl = doc.getElementsByTagName("user");
            classNode = nl.item(0).getFirstChild();
            sqlConfig.put("user", classNode.getNodeValue().trim());
            // 数据库登录密码
            nl = doc.getElementsByTagName("pwd");
            classNode = nl.item(0).getFirstChild();
            sqlConfig.put("pwd", classNode.getNodeValue().trim());

            return sqlConfig;
        } catch (DOMException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        } catch (SAXException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void main(String[] args) {
        Connection connection = null;
        HashMap<String, String> config = new HashMap<String, String>();
        // 获取对应的数据库配置属性
        config = getSQLConfig();
        try {
            // 加载 SQL Server 驱动程序,得到 Connection 对象
            Class.forName(config.get("driver"));
            // 建立数据库连接
            connection = DriverManager.getConnection(config.get("url") + config.get("dbName"), config.get("user"), config.get("pwd"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 提示语
        System.out.println("Connect successfully ! ");
        try {
            // 关闭数据库连接
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

五、json 类型文件

5.1 前期准备

数据库配置文件放在 json 文件,文件名为 XXXX.json,这里作为示例,文件名称为 dbConfig.json

引入架包:sqljdbc4.jar、json.jar、commons-io.jar

4.2 dbConfig.json 文件

{
  "driver": "com.microsoft.sqlserver.jdbc.SQLServerDriver",
  "url": "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=",
  "dbName": "dbName",
  "user": "root",
  "pwd": "root"
}

5.3 示例代码:

package dbutil;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;

import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class ConnectTest_4 {
    /**
     * @description 读取数据库配置属性
     * @return
     */
    public static HashMap<String, String> getSQLConfig() {
        try {
            String s = FileUtils.readFileToString(new File("src/dbutil/dbConfig.json"), "UTF-8");
            JSONObject jsonObject = new JSONObject(s);
            HashMap<String, String> config = new HashMap<String, String>();
            config.put("driver", jsonObject.getString("driver"));
            config.put("url", jsonObject.getString("url"));
            config.put("dbName", jsonObject.getString("dbName"));
            config.put("user", jsonObject.getString("user"));
            config.put("pwd", jsonObject.getString("pwd"));
            return config;
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Connection connection = null;
        HashMap<String, String> config = new HashMap<String, String>();
        // 获取对应的数据库配置属性
        config = getSQLConfig();
        try {
            // 加载 SQL Server 驱动程序,得到 Connection 对象
            Class.forName(config.get("driver"));
            // 建立数据库连接
            connection = DriverManager.getConnection(config.get("url") + config.get("dbName"), config.get("user"),
                    config.get("pwd"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 提示语
        System.out.println("Connect successfully ! ");
        try {
            // 关闭数据库连接
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

相关文章

  • 读取配置文件信息连接数据库

    Java读取配置文件信息连接数据库创建java 工程,导入PGsql 驱动包结构如下: 数据库配置文件内容; im...

  • thinkphp——数据库和模型

    连接数据库 修改database.php配置文件,配置数据库的连接 return [// 数据库类型'type' ...

  • Java读取不同类型数据库配置文件连接数据库

    一、前言 JDK 版本:1.8 开发环境:Eclipse 数据库:SQL Server 外部架包:sqljdbc4...

  • 连接数据库(JDBC)

    JDBC:Java DataBase Connection Java数据库连接,用来操作关系型数据库。 连接数据库...

  • SpringBoot配置MySQL多数据源

    1、先配置数据库连接文件 在连接文件中,设置多个数据库连接 2、AAA数据库连接配置文件 3、BBB数据库连接配置...

  • mybatis常用jdbcType数据类型对应javaType

    jdbcType介绍 数据库列字段都是有类型的,不同的数据库有不同的类型。为了表示这些数据类型,Java源码是采用...

  • JDBC连接

    数据库连接建立后返回值为connection类型因此通过 方式定义链接数据库方法。返回具体类型为java.sql....

  • JDBC类型

    1.JDBC类型 1.1简介 数据库列字段都是有类型的,不同的数据库有不同的类型。 为了表示这些数据类型,Java...

  • 数据库

    数据库开发 JDBC 针对不同的数据库,使用JAVA程序进行连接时会需要针对不同的数据库的接口进行编程;学习,开发...

  • 2018-06-08

    Flask连接数据库 数据库配置文件 主app文件

网友评论

      本文标题:Java读取不同类型数据库配置文件连接数据库

      本文链接:https://www.haomeiwen.com/subject/xduqpctx.html