读取数据库内容

 1 package dsa;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 
 8 public class Test_demo {
 9 static String sql = "select * from information_test";//SQL语句    输入表名information_test
10 static ResultSet rs = null;
11 public static final String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";//输入数据库名test
12 public static final String user = "root";//用户名
13 public static final String password = "rootroot";//密码
14 public static Connection conn = null;
15 public static PreparedStatement ps = null;    
16 public static void main(String[] args) {
17     try {
18         Class.forName("com.mysql.cj.jdbc.Driver");//指定连接类型
19         conn = DriverManager.getConnection(url, user, password);//获取连接
20         ps = conn.prepareStatement(sql);//准备执行语句
21         } 
22     catch (Exception e) {
23         e.printStackTrace();
24         }    
25 
26     //显示数据
27     try {
28             rs = ps.executeQuery();//执行语句
29 
30             while (rs.next()) {
31                 int co2 = rs.getInt("CO2");//输入要输出的元素名
32                 int co=rs.getInt("CO");
33                 System.out.println("CO2:"+co2+"  CO:"+co);  
34             }
35             //关闭连接
36             rs.close();
37             conn.close();
38             ps.close();
39     } 
40     catch (SQLException e) {
41         e.printStackTrace();    
42         }
43     }
44 
45 }
原文地址:https://www.cnblogs.com/moomcake/p/11831873.html