zoukankan      html  css  js  c++  java
  • java链接mysql数据库的三种链接方式

    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("连接数据库的第一种方式
    ");
    	}
    	
    	/**
    	 * 第二种连接方式
    	 * @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("连接数据库的第二种方式
    ");
    	}
    	
    	/**
    	 * 第三种链接方式  (建议使用的方式)
     	 * @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){}
    				  
    		  }
    	}
    

      

  • 相关阅读:
    CMD文件分析
    #ifdef __cplusplus
    nginx查看post请求日志
    JNI常见错误1
    include、include_once与require、require_once区别
    在Windows下利用Eclipse调试FFmpeg
    在Windows下利用MinGW编译FFmpeg
    图文详解YUV420, yuv格式2
    yuv rgb 像素格式1
    libyuv 编译for ios
  • 原文地址:https://www.cnblogs.com/panxinqi/p/6487127.html
Copyright © 2011-2022 走看看