JDBC(Java Database Connectivity)是Java语言操作关系型数据库的API。在使用JDBC连接MySQL的过程中,我们可以通过配置文件来连接MySQL数据库。
以下是一个简单的配置文件示例:
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8jdbc.username=rootjdbc.password=123456
在配置文件中,我们定义了MySQL驱动程序的类名、数据库连接的URL、用户名和密码。我们可以使用以下代码来读取并解析配置文件:
import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class JDBCUtil {private static String driver;private static String url;private static String username;private static String password;static {try {InputStream inputStream = JDBCUtil.class.getResourceAsStream("/jdbc.properties");Properties properties = new Properties();properties.load(inputStream);driver = properties.getProperty("jdbc.driver");url = properties.getProperty("jdbc.url");username = properties.getProperty("jdbc.username");password = properties.getProperty("jdbc.password");Class.forName(driver);} catch (IOException | ClassNotFoundException e) {e.printStackTrace();}}// 获取数据库连接public static Connection getConnection() throws SQLException {return DriverManager.getConnection(url, username, password);}}
在JDBCUtil类的静态代码块中,我们通过InputStream从配置文件中读取数据,然后使用Properties类解析配置文件中的属性。通过Class.forName()方法加载MySQL驱动程序的类,最终可以通过getConnection()方法获取到数据库连接。
使用配置文件连接MySQL可以方便地管理MySQL连接的参数,避免了代码中硬编码的问题。同时,配置文件的修改也可以不影响Java代码的运行。