panxinqi
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;
import java.sql.Connection;


public class ConnectMysql{
	
	private  String url = "jdbc:mysql://localhost:3306/dinner";
	private  String user = "root";
	private  String password = "root";
	
	/**
	 * 第一种连接方式
	 * @throws Exception
	 */
	public  void test1() throws Exception{
		//1.创建驱动程序类对象
		Driver driver = new com.mysql.jdbc.Driver();
		
		//2.设置用户名和密码
		Properties props = new Properties();
		props.setProperty("user", user);
		props.setProperty("password", password);
		
		//3.连接数据库,返回连接对象
		Connection con = driver.connect(url, props);
		
		//4.打印输出
		System.out.println(con);
		System.out.println("连接数据库的第一种方式\n");
	}
	
	/**
	 * 第二种连接方式
	 * @throws Exception
	 */
	public void  test2() throws Exception{
		
			Driver driver = new com.mysql.jdbc.Driver();
			
			//1.注册驱动程序类对象
			DriverManager.registerDriver(driver);
			
			//2.链接到数据库
			Connection con  = DriverManager.getConnection(url,user,password);
			
			//3.打印输出
			System.out.println(con);
			System.out.println("连接数据库的第二种方式\n");
	}
	
	/**
	 * 第三种链接方式  (建议使用的方式)
 	 * @throws Exception
	 */
		public void test3() throws Exception{
			//Driver driver = new com.mysql.jdbc.Driver();
			
			//1.通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
				Class.forName("com.mysql.jdbc.Driver");
			
			//2.连接到具体的数据库
				
			Connection conn = DriverManager.getConnection(url, user, password);
			
			//3.打印输出
			System.out.println(conn);

		}
		public static void main(String[] args) {
			
			ConnectMysql con1 = new ConnectMysql();
				  try{
					  con1.test1();
				  }catch(Exception e){}
				  
				  ConnectMysql con2 = new ConnectMysql();
				  try{
					  con1.test2();
				  }catch(Exception e){}
				  
				  
				  ConnectMysql con3 = new ConnectMysql();
				  try{
					  con3.test3();
				  }catch(Exception e){}
				  
		  }
	}

  

分类:

技术点:

相关文章:

  • 2021-07-26
  • 2021-04-27
  • 2021-10-14
  • 2021-08-06
  • 2021-11-07
  • 2022-02-01
  • 2022-02-18
  • 2021-06-10
猜你喜欢
  • 2021-12-03
  • 2022-12-23
  • 2021-10-24
  • 2018-03-01
  • 2021-05-14
  • 2021-07-15
  • 2021-10-06
相关资源
相似解决方案