Прочитайте dbURL, пользователя и пароль из файла свойств - PullRequest
0 голосов
/ 05 мая 2018
package com.j2ee.jdbc.firstProgram;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.mysql.jdbc.Driver;


public class JDBC_Properties {


    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            //Load The Driver

            Class.forName("com.mysql.jdbc.Driver").newInstance();

            /*Driver driverRef = new Driver();
            DriverManager.registerDriver(driverRef);*/


            //Get DB Connection
            //String dbUrl ="jdbc:mysql://localhost:3306/studentdb?user=root&password=root";
            String dbUrl ="jdbc:mysql://localhost:3306/studentdb";
            String fileLocation ="D:\\J2EE_Workspace\\db_Credentials.properties";

            FileReader reader = new FileReader(fileLocation);
            Properties properties1 = new Properties();
            properties1.load(reader);
            con = DriverManager.getConnection(dbUrl,properties1);

            //Process SQL Queries
            String query ="select * from students_info";
            stmt=con.createStatement();
            rs=stmt.executeQuery(query);

            //Process the Results
            while (rs.next())
            {
                int regno = rs.getInt("regno");
                String firstName = rs.getString("firstname");
                String middleName = rs.getString("middlename");
                String lastName = rs.getString("lastname");
                String email = rs.getString("email");
                int mobile= rs.getInt("mobile");
                int day = rs.getInt("birth_day");
                String month = rs.getString("birth_month");
                int year = rs.getInt("birth_year");

                System.out.println("Regno : "+regno);
                System.out.println("Name : "+firstName+" "+middleName+" "+lastName);
                /*System.out.println("Middle Name : "+middleName);
                System.out.println("Last name : "+lastName);*/
                System.out.println("Email : "+email);
                System.out.println("Mobile : "+mobile);
                System.out.println("DOB : "+day+"-"+month+"-"+year);
                System.out.println();
            }

            }

        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            //Close all the JDBC Objects
            try
            {
                if(con!=null)
                {
                    con.close();
                }
                if(rs!=null)
                {
                    rs.close();
                }
                if(stmt!=null)
                {
                    stmt.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

} //END OF CLASS

Вышеуказанная программа считывает имя пользователя и пароль из файла свойств. Но мне нужно прочитать «dbUrl» из файла свойств. Поэтому мне не нужно менять программу, если я переключаю базу данных

db_Credentials.properties

пользователь = корень

пароль = корень

Я хочу прочитать dbURL из файла свойств, но

con = DriverManager.getConnection(dbUrl,properties1);

принимает только 2 аргумента.

1 Ответ

0 голосов
/ 07 мая 2018

Вы можете просто добавить значение свойства dbUrl в файл db_Credentials.properties :

dbUrl = jdbc:mysql://localhost:3306/studentdb
user = root
password = root

Затем считайте предоставленное значение как простое свойство String и передайте его в качестве аргумента url при вызове одного из перегруженных методов getConnection:

public class JDBC_Properties {

    private static final java.lang.String DB_URL_PROP_KEY = "dbUrl";

    public static void main(String[] args) {
        //...
        try {
            //...
            //Get DB Connection
            String fileLocation ="D:\\J2EE_Workspace\\db_Credentials.properties";
            Properties properties1 = new Properties();
            properties1.load(new FileReader(fileLocation));
            con = DriverManager.getConnection(properties1.getProperty(DB_URL_PROP_KEY), properties1);

            //Process SQL Queries
            //...
        }
        catch (Exception e) {
           //...
        }
        finally {
           //...
        }
    }
} //END OF CLASS

EDIT

Вам может потребоваться удалить свойство dbUrl из объекта Properties, чтобы избежать получения ошибки в случае, если базовый драйвер DB вызывает исключение для нераспознаваемого свойства:

public class JDBC_Properties {

    private static final java.lang.String DB_URL_PROP_KEY = "dbUrl";

    public static void main(String[] args) {
        //...
        try {
            //...
            //Get DB Connection
            String fileLocation ="D:\\J2EE_Workspace\\db_Credentials.properties";
            Properties properties1 = new Properties();
            properties1.load(new FileReader(fileLocation));
            // read the database url property value then remove the entry
            String dbUrl = properties1.getProperty(DB_URL_PROP_KEY);
            properties1.remove(DB_URL_PROP_KEY);
            con = DriverManager.getConnection(dbUrl, properties1);

            //Process SQL Queries
            //...
        }
        catch (Exception e) {
           //...
        }
        finally {
           //...
        }
    }
} //END OF CLASS
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...