Home > front end >  How to connect to MySQL database via plain text file?
How to connect to MySQL database via plain text file?

Time:11-01

I would like to improve my code so that it would be possible to connect to the database using a text file, but not setting the database connection from the IntelliJ or Eclipse view only from the text file (we set the login, password, path, etc. there).

public class SQL {
    public static Connection Connect() throws ClassNotFoundException, SQLException, IOException {
        Properties props = new Properties();
        FileInputStream in = new FileInputStream("E:/file.txt");
        props.load(in);
        in.close();

        String driver = props.getProperty("jdbc.driver");
        if (driver != null) {
            Class.forName(driver);
        }

        String url = props.getProperty("jdbc.url");
        String username = props.getProperty("jdbc.username");
        String password = props.getProperty("jdbc.password");
        return DriverManager.getConnection(url, username, password);
    }

The problem is with this line:

FileInputStream in = new FileInputStream("E:/file.txt")

How can I set the path to the FileInputStream with a txt file?

So far, I can set the login, password and URL using a text file, but I still have a problem how to correctly pass the address of this text file (in a text file)

CodePudding user response:

By convention, java properties files have the .properties extension. I would suggest that you name the file jdbcconn.properties. Put that file in the same folder as file SQL.class. Then in your java code you can do something like the following.

Properties props = new Properties();
java.io.InputStream is = getClass().getResourceAsStream("jdbcconn.properties");
props.load(is);

Refer to javadoc of class java.lang.Class

Note that in Eclipse IDE, you create the jdbcconn.properties file in the same folder as file SQL.java and when you build your project, Eclipse will automatically copy file jdbcconn.properties to the same folder as file SQL.class

CodePudding user response:

What you are looking for is to configure you application from an external source. Lucky enought, Java provides an API that helps manage your external configuration as keys/values with the properties files.

By default your configuration file has .properties extension, i.e. config.properties. If you are using a maven project, your configuration file will be in this folder /src/main/resources.

Then you will be able to call your file as mentionned in the previous answer.

  • Related