JDBC連接數據庫(1)

      /*
       * Driver 是一個接口:數據庫廠商必須提供實現的接口。能從其中獲取數據庫連接。
       * 可以通過Driver的實現類對象獲取數據庫連接。
       * 加入MySQL驅動程序。
       * 在當前目錄下新建lib目錄。
       * build path --》add to BuildPath*/
	public void testDriver()throws SQLException{
		//1創建一個Driver實現類的對象。
		Driver driver=new com.mysql.jdbc.Driver();//與程序耦合太大。
		//2準備連接數據庫的基本信息:url,user,password
		String url="jdbc:mysql://127.0.0.1:3306/test";
		Properties info=new Properties();
		info.put("user","root");
		info.put("password","root");
		//3調用Driver接口的connect方法,獲取數據庫連接。
		Connection connection=driver.connect(url, info);
		System.out.println(connection);
		
	}
最簡單的情況:
public void testMyConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","root");
System.out.println(connection);
 

/*
* 編寫一個通用的方法,在不修改源程序的情況下獲取任何數據庫的連接。
* 解決方案:把數據庫驅動Driver實現類的全類名,url,user,password放入一個配置文件中,通過修改配置
* 文件的方式實現和具體的數據庫解耦。*/

	public Connection getConnection()throws Exception{
		String driverClass=null;
		String jdbcUrl=null;
		String user=null;
		String password=null;
		//讀取類路徑下的jdbc.properties文件。
		InputStream in=
				getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		Properties properties=new Properties();
		properties.load(in);
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("jdbcUrl");
		user=properties.getProperty("user");
		password=properties.getProperty("password");
		
		Driver driver=
				(Driver) Class.forName(driverClass).newInstance();
		
		Properties info=new Properties();
		info.put("user", user);
		info.put("password", password);
		Connection connection=driver.connect(jdbcUrl, info);
		return connection;
	}
	public void testGetConnection1() throws Exception{
		System.out.println(getConnection());
	}
	//使用DriverManager
	public void testDriverManager() throws SQLException, IOException, ClassNotFoundException{
		/*
		 * DriverManager是驅動的管理類。
		 * 1.可以通過重載getConnection()方法獲取數據庫連接,較爲方便
		 * 2.可以管理多個驅動程序。*/
		
		//1準備數據庫的4個字符串。
		//驅動的全類名。
		String driverClass=null;
		String jdbcUrl=null;
		String user=null;
		String password=null;
		//讀取類路徑下的jdbc.properties文件。
		InputStream in=
				getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		Properties properties=new Properties();
		properties.load(in);
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("jdbcUrl");
		user=properties.getProperty("user");
		password=properties.getProperty("password");
		//2加載數據庫驅動程序。(對應的Driver實現類中註冊驅動的靜態代碼塊。)
		//DriverManager.registerDriver(Class.forName(driverClass).newInstance());
		//此處可以註冊,他可以管理多個驅動程序。
		Class.forName(driverClass);
		//通過DriverManager的getConnection()方法獲取數據庫連接。
		Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
		System.out.println(connection);
	}
	public Connection getConnection2() throws IOException, ClassNotFoundException, SQLException{
		//1.準備連接數據庫的4個字符串。
		  //1)z創建jdbc.properties對象。
		Properties properties=new Properties();
		  //2)加載對應的輸入流。
		InputStream in=
				this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		//3)加載2)對應的輸入流 
		  properties.load(in);
		//4)具體決定user,password等4個字符串。
		  String user=properties.getProperty("user");
		  String password=properties.getProperty("password");
		  String driver=properties.getProperty("driver");
		  String jdbcUrl=properties.getProperty("jdbcUrl");
		//2.加載數據庫驅動(對應的Driver實現類中有註冊驅動的靜態代碼塊)
		  Class.forName(driver);
		//3.通過DriverManager的getConnection()方法獲取數據庫連接。
		  return DriverManager.getConnection(jdbcUrl,user,password);
	}
	public void testGetConnection() throws IOException, ClassNotFoundException, SQLException{
		System.out.println(getConnection2());
	}
	/*
	 * 通過JDBC向數據庫插入數據。*/
	public void testStatement() throws IOException, ClassNotFoundException, SQLException{
		/*Statement:用於執行SQL語句的對象
		 * * 通過Connection的CreateStatement()方法來獲取
		 * *通過executeUpdate(sql)可以執行SQL語句
		 * *傳入的SQL可以是insert,update,delete但不能是Select
		 * Connection,Statement都是應用程序和數據庫服務器的連接資源。使用後一定要關閉。
		 * 需要在finally關閉。*/
		//1獲取數據庫連接
		Connection conn=null;
		Statement statement=null;
		try{
		conn=getConnection2();
		//3準備插入的SQL語句
	//	String sql="insert into customers(name,email,birth)values('abc','[email protected]','1992-12-28')";
	//	String sql="delete from customers where ID= 1";
		String sql="update  customers set  name= 'Tom' "+"Where id = 2";
		System.out.println(sql);
		//執行插入
		//1)獲取操作Statement對象
		statement=conn.createStatement();
		//2)調用Statement的executeUpdate(sql)
		statement.executeUpdate(sql);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
	try{	//5,關閉Statement對象
		if(statement!=null)
		statement.close();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		//2.關閉連接
		if(conn!=null)
		conn.close();
		}
	}
	}
	public void update(String sql) throws SQLException{
	
		Connection conn=null;
		Statement statement=null;
		try{
		conn=JDBCTools.getConnection();
		statement=conn.createStatement();
		statement.executeUpdate(sql);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
	    JDBCTools.release(null,statement, conn);
	}
}
	/*
	 * ResultSet:結果集,封裝了使用JDBC進行查詢的結果。
	 * 1調用Statement對象的executeQuery(Sql)可以得到結果集
	 * 2ResultSet:返回的實際上就是一張數據表,有一個指針指向數據表的第一行的前面。
	 * 可以調用next()方法檢測下一行是否有效,若有效則下移相當於hasNext和next結合體
	 * 3.當指針定位到一行時通過調用getXxx(index)或getXxx(columnName)
	 * 獲取每一列的值getXxx(1),getString(name)
	 * 4ResultSet當然也需要進行關閉。*/
	public void testResultSet(){
	 //獲取id=4的customers數據表的記錄,並打印
		Connection conn=null;
		Statement statement=null;
		ResultSet rs=null;
		try{
		//1獲取Connection
		conn=JDBCTools.getConnection();
		//2獲取Statement
		statement=conn.createStatement();
		//3準備SQL
		String sql="SELECT * "+
		"From customers ";
		//4執行查詢,得到ResultSet
		rs=statement.executeQuery(sql);
		//5處理ResultSet
		while(rs.next()){
			int id=rs.getInt(1);
			String name=rs.getString("name");
			String email=rs.getString(3);
			Date birth=rs.getDate(4);
			System.out.println(id);
			System.out.println(name);
			System.out.println(email);
			System.out.println(birth);
			
		}
		//6關閉數據庫連接資源。
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCTools.release(rs, statement, conn);
		}
		
		
	}
其中jdbc.properties文件內容爲:

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/atguigu
user=root
password=root
放在src目錄下。

封裝的JDBCTools.java

/*
 * 操作JDBC的工具類,其中封裝了一些工具方法
 * 通過讀取配置文件從數據庫服務器獲取一個連接*/
public class JDBCTools {
	public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException{
		//1.準備連接數據庫的4個字符串。
		  //1)z創建jdbc.properties對象。
		Properties properties=new Properties();
		  //2)加載對應的輸入流。
		InputStream in=JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
		//3)加載2)對應的輸入流 
		  properties.load(in);
		//4)具體決定user,password等4個字符串。
		  String user=properties.getProperty("user");
		  String password=properties.getProperty("password");
		  String driver=properties.getProperty("driver");
		  String jdbcUrl=properties.getProperty("jdbcUrl");
		//2.加載數據庫驅動(對應的Driver實現類中有註冊驅動的靜態代碼塊)
		  Class.forName(driver);
		//3.通過DriverManager的getConnection()方法獲取數據庫連接。
		  return DriverManager.getConnection(jdbcUrl,user,password);
	}
	/*
	 *關閉Statement,Connection */
	public static void  release(ResultSet rs,Statement statement,Connection conn){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	    if(statement!=null){
	    	  try{
	    		  statement.close();
	    	  }catch(Exception e2){
	    	  e2.printStackTrace();
	        }
	      }
	      if(conn!=null){
	    	  try{
	    		  conn.close();
	    	  }catch(Exception e2){
	    	  e2.printStackTrace();
	      }
	    }
	}
}



發佈了38 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章