https://blog.csdn.net/huwentao0305/article/details/53378755
Save the code to verify that you can connect to MySQL
Recorded the login password 123456789 (!!! I forgot it at the beginning, I happened to try it right
import java.sql.*; public class SqlConnection { //here is the SqlConnection class /* *java connects to mysql database *1. Load the driver *2. The database connection string "jdbc:mysql://localhost:3306/database name?" *3. Database login name *3. Database login password */ 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 void TheSqlConnection() { //1. Load the driver try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException 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 (); } Connection conn = null; try { conn = 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 (); } // The database will be closed after opening if(conn!=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace (); conn=null; } } } }
public class MainCalss { public static void main(String[] args) { // TODO auto-generated method stub new SqlConnection().TheSqlConnection(); } }