Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

java - How do I read a properties file and connect a MySQL database?

I need to connect my MySQL database from within Java program, for that I have to use JDBC.

I need to supply it with the necessary connection parameters. And I have to store these parameters in a separate configuration file to be passed as an argument to your Java program during execution. A sample db.properties file has been provided to me for my reference. The five lines of the file correspond to the host, port, database name, username and password for the database. I need to change the parameters according to your individual system setup.

How do I proceed with this? How do I connect MySQL database?

basically, I have a createdb.sql file . I have to run that file in mysql. It will create a database. Now I need to populate the database. I have two input files. I need to write a program in java that takes the names of the input data files as command line parameters, parses the files, and populates the data contained within them into your database via JDBC

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can save you db.properties file to an external fixed location, and access it for later to retrieve your connection properties:

Properties props = new Properties();
FileInputStream in = new FileInputStream("/external/configuration/dir/db.properties");
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");

Connection con = DriverManager.getConnection(url, username, password);

Then, on every environment you can have a different copy of your database settings, without having to change your application file (JAR, ER, or whatever).

Sample database connection properties file:

# Oracle DB properties
#jdbc.driver=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc:oracle:thin:@localhost:1571:MyDbSID
#jdbc.username=root
#jdbc.password=admin

# MySQL DB properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/MyDbName
jdbc.username=root
jdbc.password=admin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...