The first code written in java to connect to MySQL

import java.sql.*;
public class Test {
	
	 private static final String URL="jdbc:mysql://localhost:3306/test1?";//Database connection string, where deom is the database name
     private static final String NAME="root";//Login name
     private static final String PASSWORD="123456789";//密码
	 public static void main(String[] args) {
		// TODO Auto-generated method stub
          Connection  con = null;
          Statement sql;
          ResultSet rs;
         
          try {
        	  Class.forName("com.mysql.jdbc.Driver");
          }
          catch(Exception e) {
        		System.out.println("Failed to load the driver successfully, please check whether to import the driver!");
                //Add a println, if the driver is loaded abnormally, check whether the driver is added, or whether the driver string is incorrectly added
	       e.printStackTrace ();
          }
          try {
        	  con=DriverManager.getConnection(URL,NAME,PASSWORD);
        	  System.out.println("Get database connection successfully!");
          }
          catch(SQLException e) {
        		System.out.println("Failed to get database connection!");
                //Add a println, if the connection fails, check whether the connection string or login name and password are wrong
	       e.printStackTrace ();
          }
           try {
        	   sql=con.createStatement();
        	   rs=sql.executeQuery("select * from  mess");
        	   while(rs.next()) {
        		   String number=rs.getString(1);
        		   String name = rs.getString(2);
        		   Date date = rs.getDate(3);
        		   float height = rs.getFloat(4);
        	       System.out.printf("%s\t",number);
        	       System.out.printf("%s\t",name);
        	       System.out.printf("%s\t",date);
        	       System.out.printf("%.2f\n",height);
        	   }
        	   con.close();
        	  
           }
           catch(SQLException e) {
        	   System.out.println(e);
           }
         
	}

}

SQL statement:

CREATE TABLE `mess` (
  `number` char(50) NOT NULL,
  `name` varchar(100) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `height` float DEFAULT NULL,
  PRIMARY KEY (`number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Summary: When using exception handling statements, adding some output can easily judge whether to go to this step

Guess you like

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