為了項(xiàng)目容易管理,我們經(jīng)常將變量統(tǒng)一放在resources
文件夾下,以.properties
文件進(jìn)行存儲。最常見的就是在進(jìn)行數(shù)據(jù)庫連接時(shí)配置的數(shù)據(jù)庫連接數(shù)據(jù)。
先在resources文件夾下新建jdbc.properties
文件
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/myDatabase
jdbc.username = root
jdbc.password = hwsofts08
代碼
package com.autotesting;
import java.io.IOException;
import java.util.Properties;
public class Test {
public static void main(String[] args) {
Properties properties = new Properties();
try {
properties.load(Test.class.getClassLoader().getResourceAsStream("jdbc.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
System.out.println("url is: " + url);
System.out.println("username is: " + username);
System.out.println("password is: " + password);
}
}
執(zhí)行結(jié)果:
為了連接MySQL數(shù)據(jù)庫,需要先下載mysql-connector-java
jar包。
下載地址:
https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.30
下載完成后,將mysql-connector-java-8.0.30.jar
文件復(fù)制到lib
文件夾下,然后右鍵選擇Add as Library
語句
select * from student where sid = 18;
代碼:
package com.autotesting;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class ConnData {
public static void main(String[] args) {
String sql = "select * from student where sid = ?;";
Properties properties = new Properties();
try {
properties.load(new FileInputStream(new File("src/main/resources/jdbc.properties")));
// 獲取jdbc.properties文件中的數(shù)據(jù)
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
// 獲取Connection
Connection connection = DriverManager.getConnection(url, username, password);
// 獲取PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 設(shè)置條件字段值
preparedStatement.setObject(1, 18);
// 調(diào)用查詢方法獲取結(jié)果集
ResultSet resultSet = preparedStatement.executeQuery();
// 從結(jié)果集獲取查詢數(shù)據(jù)
while(resultSet.next()){
String nameValue = resultSet.getObject("sname").toString();
String genderValue = resultSet.getObject("gender").toString();
String sidValue = resultSet.getObject("sid").toString();
System.out.println("sname is "+ nameValue + "; gender is " + genderValue + "; sid is " + sidValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
執(zhí)行結(jié)果
-------
如果您覺得對您有幫助,請幫忙點(diǎn)一下公眾號文中和最底部的廣告,點(diǎn)一下就可以,謝謝~
聯(lián)系客服