需要的jar包

一共是两个:一个是druid的jar包一个是mysql数据库的驱动jar包
image.png

实现的思路

_ 1.导入jar包 , 创建druid的配置文件druid.properties(名字可以随便起) 配置文件需要放到java文件夹得src目录下面
2.使用类加载器,加载druid的配置文件
3,使用durid得到数据库的连接
//3.1 先得到druid的数据源
DataSource ds = DruidDataSourceFactory.createDataSource(properties);
//3.2 得到数据库的连接
Connection connection = ds.getConnection();
4.执行一个简单的查询语句 connect.perperStatement(sql) 返回一个preperstatement对象
5开始查询 preparestatement.executeQuery() 返回一个结果接对象其实是一个set集合
6.使用while循环遍历set集合,并且得到里面的值
//使用迭代器遍历Resultset集合
while (resultSet.next()){
String name = resultSet.getString(“name”);
System.out.println(name);
}

注意你要根据字段里面的属性值,调用响应的getxxx方法 ,如果不知道字段里面存放的是什么值,
可以出在sqlyog里面使用describe 查看表的结构
/

_

代码展示:

配置文件代码

1,先看看配置文件里面写的什么
image.png

java代码

需要主义的是 在对查询到的数据进行遍历的时候的方法。

  1. public class getdruidConnection {
  2. public static void main(String[] args) throws Exception {
  3. //2.我们把数据库的连接驱动和数据的连接都放在druid.properties文件下面了,所以我们要加载配置文件
  4. // 注意的是 druid 需要手动加载配置文件 c3p0可以自动加载配置文件
  5. /**
  6. 使用类加载器加载配置文件
  7. */
  8. Properties properties = new Properties();
  9. InputStream inputStream = getdruidConnection.class.getClassLoader().getResourceAsStream("druid.properties");
  10. try {
  11. properties.load(inputStream);
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. System.out.println("加载druid配置文件出错");
  15. }
  16. //3,使用durid得到数据库的连接
  17. //3.1 先得到druid的数据源
  18. DataSource ds = DruidDataSourceFactory.createDataSource(properties);
  19. //3.2 得到数据库的连接
  20. Connection connection = ds.getConnection();
  21. System.out.println(connection);
  22. //4.执行一个简单的查询语句 connect.perperStatement(sql) 返回一个preperstatement对象
  23. PreparedStatement preparedStatement = connection.prepareStatement("select * from luo ;");
  24. //5开始查询 preparestatement.executeQuery 返回一个结果接对象其实是一个set集合
  25. ResultSet resultSet = preparedStatement.executeQuery();
  26. //使用迭代器遍历Resultset集合
  27. while (resultSet.next()){
  28. String name = resultSet.getString("name");
  29. System.out.println(name);
  30. }
  31. }
  32. }