java连接mysql数据库例子代码

记得设置时区,数据库编码在URL中,否则连接不上

 1     @RequestMapping(value="/record")
 2     public String record() {
 3         try {
 4             Class.forName("com.mysql.cj.jdbc.Driver");
 5             String url = "jdbc:mysql://127.0.0.1/eam?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8";
 6             String username = "root";
 7             String pass = "root";
 8             try {
 9                 Connection con = DriverManager.getConnection(url, username, pass);
10                 Statement st = con.createStatement();
11                 ResultSet rs = st.executeQuery("select * from operation");
12                 while(rs.next()) {
13                     System.out.println(rs.getInt(1));
14                     System.out.println(rs.getString(2));
15                     System.out.println(rs.getString(3));
16                     System.out.println(rs.getString(4));
17                 }
18             } catch (SQLException e) {
19                 // TODO Auto-generated catch block
20                 System.out.println("数据库连接失败"+e.getMessage());
21             }
22             
23         } catch (ClassNotFoundException e) {
24             // TODO Auto-generated catch block
25             System.out.println("驱动程序加载失败");
26         }
27         System.out.println("进入record");
28         return "record";
29     }

猜你喜欢

转载自www.cnblogs.com/lijurui/p/8906377.html