如何读取属性文件并连接MySQL数据库? [英] How do I read a properties file and connect a MySQL database?

查看:176
本文介绍了如何读取属性文件并连接MySQL数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Java程序中连接我的MySQL数据库,因为我必须使用JDBC。

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

我需要为它提供必要的连接参数。我必须将这些参数存储在一个单独的配置文件中,以便在执行期间作为参数传递给Java程序。已提供示例 db.properties 文件供我参考。该文件的五行对应于数据库的主机,端口,数据库名称,用户名和密码。我需要根据您的个人系统设置更改参数。

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.

我该如何处理?如何连接MySQL数据库?

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

基本上,我有一个createdb.sql文件。我必须在mysql中运行该文件。它将创建一个数据库。现在我需要填充数据库。我有两个输入文件。我需要在java中编写一个程序,它将输入数据文件的名称作为命令行参数,解析文件,并通过JDBC将包含在其中的数据填充到数据库中

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

推荐答案

首先,您需要 mysql jdbc connector 。下载库并将jar添加到类路径中。

First, you need the mysql jdbc connector. Download the library and add the jar to the classpath.

接下来的步骤(在您的应用程序中)是加载jdbc驱动程序并且创建连接

The next steps (in your application) are to load the jdbc driver and to create a connection:

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
                  "jdbc:mysql://[host][:port]/[database]", username, password);

所以你必须阅读配置文件,提取值并创建连接字符串(主机) ,端口,数据库部分)。

So you'll have to read the config file, extract the values and create the connection string (host, port, database part).

如果你正在使用eclipse:在你的项目中创建一个'lib'文件夹,将jar复制到该文件夹​​,右键单击jar并将其添加到构建路径。

if you're using eclipse: create a 'lib' folder in your project, copy the jar to that folder, right-click the jar and add it to the build path.

如果你手动执行应用程序,你就这样做了:

if you're executing the application manually, and you did it like this:

java com.example.MyApplication

现在这样做:

java -cp .;path/to/jarfile/connector.jar com.example.MyApplication

(我不确定lib是否被命名为connector .jar,在这里使用正确的文件名)

(I'm not sure if the lib is named connector.jar, use the correct filename here)

这是有关添加库的教程,也就是为java和javac设置类路径。你需要理解这个概念!

Here is tutorial on adding libraries aka "setting the classpath" for java and javac. You need to understand this concept!

这篇关于如何读取属性文件并连接MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆