新建一个数据库properties文件 dataSource.properties
新建一个测试类
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DataTest {
private static String fileName = "dataSource.properties";
public static void main(String[] args) {
Properties prop = new Properties();
try {
//读取属性文件
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);prop.load(inputStream); ///加载属性列表
String name = prop.getProperty("name");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(name);//获取连接类型
Connection con = DriverManager.getConnection(url,user,password);//获取连接
String sql = "select * from user";
PreparedStatement pst = con.prepareStatement(sql);//准备执行语句
ResultSet result = pst.executeQuery();//执行语句,得到结果集
List<String> list = new ArrayList();
while(result.next()){
list.add(result.getString(2));
System.out.println(result.getString(1));
System.out.println(result.getString(2));
System.out.println(result.getString(3));
}
result.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
原文地址:https://www.cnblogs.com/zjf6666/p/9055555.html