1. 程式人生 > >JDBC資料庫基本操作(一)

JDBC資料庫基本操作(一)

1.什麼是JDBC?

在看JDBC的概念之前先來看看什麼是資料庫驅動。

資料庫驅動中驅動的概念和平時聽到的那種驅動的概念是一樣的,比如平時購買的音效卡,網絡卡直接插到計算機上面是不能用的,必須要安裝相應的驅動程式之後才能夠使用音效卡和網絡卡,同樣道理,我們安裝好資料庫之後,我們的應用程式也是不能直接使用資料庫的,必須要通過相應的資料庫驅動程式,通過驅動程式去和資料庫打交道。

SUN公司為了簡化、統一對資料庫的操作,定義了一套Java操作資料庫的規範(介面),稱之為JDBC(Java Data Base Connectivity)。這套介面由資料庫廠商去實現,這樣,開發人員只需要學習jdbc介面,並通過jdbc載入具體的驅動,就可以操作資料庫。

綜上,JDBC是一個獨立於特定資料庫管理系統、通用的SQL資料庫存取和操作的公共介面,定義了用來訪問資料庫的標準java類庫,使用這個類庫可以以一種標準的方法方便地訪問資料庫資源。JDBC的目標是使程式設計師使用JDBC可以連線任何提供了JDBC驅動程式的資料庫系統,這樣使得程式設計師無需對特定的資料庫系統的特點有過多的瞭解,從而大大簡化和加快了開發過程。

2.JDBC API

JDBC API是一系列的介面,它使得應用程式能夠進行資料庫連線,執行SQL語句,並且得到返回結果。資料庫廠商使用的Java.sql.Driver介面是所有JDBC驅動程式需要實現的介面,在java程式中不需要直接去訪問實現了Driver介面的類,而是由驅動程式管理器類java.sql.DriverManager去呼叫這些Driver實現。

3.JDBC獲取資料庫的連線

3.1 使用Driver介面獲取資料庫的連線

package com.test.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

import org.junit.Test;
/*
 * 編寫一個通用的方法,在不修改源程式的條件下,可以獲取任何資料庫的連線
 * */

public class JDBCTest {	
	public Connection getConnection() throws Exception{
//準備連線資料庫的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); //讀取properties檔案內容 driverClass=properties.getProperty("driver"); jdbcUrl=properties.getProperty("jdbcUrl"); user=properties.getProperty("user"); password=properties.getProperty("password"); //通過反射建立java物件 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; } @Test public void testGetConnection() throws Exception{ System.out.println(getConnection()); } }

 jdbc.properties

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3303/extra
user=root
password=0404

3.2 使用DriverManager類獲取資料庫連線

通過DriverManager連線資料庫的基本步驟分為:

①準備連線資料庫的4個字串,driverClass,jdbcUrl,user,password;

1).獲取類路徑下的jdbc.properties檔案

2).讀取properties檔案內容,獲取4個字串的值

②載入資料庫驅動程式;

③通過DriverManager的getConnection()方法獲取資料庫連線;

package com.test.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;

public class JDBCTest {    
    
    public Connection getConnection() throws Exception{
        //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);
        //讀取properties檔案內容
        driverClass=properties.getProperty("driver");
        jdbcUrl=properties.getProperty("jdbcUrl");
        user=properties.getProperty("user");
        password=properties.getProperty("password");
        //2.載入資料庫驅動程式
        Class.forName(driverClass);
        //3.通過DriverManager的getConnection()方法獲取資料庫連線
        Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
        return connection;
    }
    @Test
    public void testGetConnection() throws Exception{
        System.out.println(getConnection());
    } }

使用DriverManager可以註冊多個驅動程式,從而使得使用多個jdbcUrl可以連線不同的資料庫。

4.通過Statement執行更新操作

Statement是用於執行SQL語句的物件:

①通過Connection的createStament()方法來獲取;

②通過executeUpdate(sql)可以執行SQL語句;

③傳入的SQL可以是INSERT,UPDATE或DELETE,但不能是SELECT;

④關閉的順序是先關閉後獲取的,即先關閉statement,再關閉connection;

package com.test.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;

/**
 * @author Administrator
 *
 */
public class JDBCTest {	
	@Test
	public void testStatement() throws Exception{
		Connection con=null;
		Statement statement=null;
		try{
			//1.獲取資料庫連線
			con=getConnection();
			//2.準備插入的SQL連線
			String sql="INSERT INTO TEST VALUES(NULL,'B','[email protected]','2018-8-09')";
			//3.執行插入
			//1).獲取操作SQL語句的Statement物件,呼叫Connection的createStatement()方法來獲取;
			statement=con.createStatement();
			//2).呼叫Statement物件的executeUpdate(sql)執行SQL語句進行插入
			statement.executeUpdate(sql);
		}catch(Exception e){
			e.printStackTrace();
			}finally{
				//使用try...catch...是為了確保出現異常也能關閉資料庫。
				//4.關閉Statement物件
				try {
					if(statement!=null)
					statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}finally{
					//5.關閉資料庫連線
					if(con!=null)
			        con.close();
				}
		}
	}
	public Connection getConnection() throws Exception{
		//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);
		//讀取properties檔案內容
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("jdbcUrl");
		user=properties.getProperty("user");
		password=properties.getProperty("password");
		//2.載入資料庫驅動程式
		Class.forName(driverClass);
		//3.通過DriverManager的getConnection()方法獲取資料庫連線
		Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
		return connection;
	}
	@Test
	public void testGetConnection() throws Exception{
		System.out.println(getConnection());
	}
}

5.一個通用的更新資料庫的方法,包括INSERT,UPDATE,DELETE。

首先將資料庫的連線和釋放的方法封裝到工具類中:

package com.test.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;
/*
 * 操作JDBC的工具類,其中封裝了一些工具方法。
 */
public class JDBCTools {
	//獲取連線的方法
	public static Connection getConnection() throws Exception{
		//1.準備連線資料庫的4個字串
		String driverClass=null;
		String jdbcUrl=null;
		String user=null;
		String password=null;
		//獲取類路徑下的jdbc.properties檔案
		InputStream in=JDBCTools.class.getResourceAsStream("jdbc.properties");
		Properties properties=new Properties();
		properties.load(in);
		//讀取properties檔案內容
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("jdbcUrl");
		user=properties.getProperty("user");
		password=properties.getProperty("password");
		//2.載入資料庫驅動程式
		Class.forName(driverClass);
		//3.通過DriverManager的getConnection()方法獲取資料庫連線
		Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
		return connection;
	}
	@Test
	public void testGetConnection() throws Exception{
		System.out.println(getConnection());
	}
	//釋放連線的方法
	public static void release(Statement statement,Connection connection){
		//使用try...catch...是為了確保出現異常也能關閉資料庫。
		//4.關閉Statement物件
		if(statement!=null){
		try {
			statement.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		}
		if(connection!=null){
		try {
			//5.關閉資料庫連線
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	}
}

通用的更新方法,包括INSERT,UPDATE,DELETE:

package com.test.jdbc;

import java.sql.Connection;
import java.sql.Statement;
import org.junit.Test;
import com.test.jdbc.JDBCTools;

public class JDBCTest {	
	public void update(String sql){
		Connection con=null;
		Statement statement=null;
		try{
			con=JDBCTools.getConnection();
			statement=con.createStatement();
			statement.executeUpdate(sql);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCTools.release(statement, con);
		}
	}
}