获取数据库(mysql)连接

步骤:

//1.数据库连接的基本要素
	String diver = "com.mysql.cj.jdbc.Driver";
	String url = "jdbc:mysql://localhost:3306/grade"
				+ "?user=root&password=18170021&serverTimezone=UTC";

//2.加载驱动
	Class.forName(diver);

 //3.获取连接
    Connection conn = DriverManager.getConnection(url, user, password);


具体代码

package cn.edu.hbue.wmp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionDemo01 {
     
	
	
	public static void main(String args[]){
     
		
		
		//1.数据库连接的基本要素
		String diver = "com.mysql.cj.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/grade"
				+ "?user=root&password=18170021&serverTimezone=UTC";
	    
	    //2.加载驱动
	    try {
     
			Class.forName(diver);
		} catch (ClassNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    
	    //3.获取连接
	    Connection conn = null;
	    try {
     
			conn = DriverManager.getConnection(url);
		} catch (SQLException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    if(conn != null)
	    	System.out.println("成功");
	    else
	    	System.out.println("失败");
		
	}
	
	
}

你可能感兴趣的:(java与JDBC)