1. 程式人生 > >JDBC訪問資料庫的基本步驟

JDBC訪問資料庫的基本步驟

jdbc連線SQL server的步驟:

  1. 載入驅動driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; Class.forName(driver);

  2. 建立連線

      url ="jdbc:sqlserver://localhost:1433;DatabaseName=StudentDB";     
      name = "sa";    
      pwd = "sa123456";
      Connection con = DriverManager.getConnection(url, name, pwd)
    
  3. 建立執行sql的語句(Statement)Statement st=con.createStatement(); st.executeQuery(sql); String sql="select * from Student where Sno=?"; PreparedStatement ps=con.prepareStatement(sql); ps.setString(1,"1"); ps.executeQuery();

  4. 執行並處理結果(ResultSet)驅動,class.forName()ResultSet rs=statement.executeQuery(sql); while(rs.next()){ rs.getString("Sno") }

  5. 釋放資源 Connection非常佔用資源,使用後必須馬上釋放; rs.close();pst.close(); con.close();

package shop.dao;

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

public class BaseDao {

	private String url = "jdbc:sqlserver://localhost:1433;DatabaseName=PetShop";// 資料連線字串
	private String name = "sa";//資料庫使用者名稱
	private String pwd = "123123";//密碼

	public Connection con;
	public PreparedStatement pst;
	public ResultSet rs;

	public Connection getCon() {
		//連線資料庫
		try {
			//1.載入jdbc驅動.class.forName()
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			//2.與資料庫建立連線Connection con=DriverManager.getConnection(資料連線字串,資料庫使用者名稱,密碼)
			con = DriverManager.getConnection(url, name, pwd);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}

	public ResultSet Select(String sql, Object[] ps) {
		if (con == null) {
			con = getCon();
		}
		try {
		//3.傳送sql語句
			pst = con.prepareStatement(sql);
			if (ps != null)
				for (int i = 0; i < ps.length; i++) {
					pst.setObject(i + 1, ps[i]);
				}
			rs = pst.executeQuery();
			return rs;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return rs;

		}
	}

	public boolean executeUpdate(String sql, Object[] ps) {

		if (con == null) {
			con = getCon();
		}
		try {
			pst = con.prepareStatement(sql);
			for (int i = 0; i < ps.length; i++) {
				pst.setObject(i + 1, ps[i]);
			}
			int i = pst.executeUpdate();
			return i > 0 ? true : false;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} finally {
			Close();
		}

	}

	public void Close() {
		try {
			if (rs != null)
				rs.close();
			if (pst != null)
				pst.close();
			if (con != null)
				con.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}

```