java connection mysql database example code

Remember to set the time zone, the database is encoded in the URL, otherwise it will not connect

 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("Database connection failed"+ e.getMessage());
 21              }
 22              
23          } catch (ClassNotFoundException e) {
 24              // TODO Auto-generated catch block 
25              System.out.println("Driver loaded Failed" );
 26          }
 27          System.out.println("Enter record" );
 28          return "record" ;
 29      }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324692437&siteId=291194637