1. 程式人生 > >使用JDBC連線Oracle資料庫和使用連線池連線Oracle資料庫的程式碼解析

使用JDBC連線Oracle資料庫和使用連線池連線Oracle資料庫的程式碼解析

這裡連線的是oracle資料庫。

JDBC是什麼:JDBC是java資料庫連線技術的簡稱,提供連線各種常用資料庫的能力。

客戶端傳送請求給應用伺服器,應用伺服器通過JDBC連線到資料庫伺服器,查詢資料庫中的資料,返回一個結果集,再把結果集轉換成實體類傳遞給客戶端。

JDBC連線資料庫的步驟:載入驅動、建立連線、執行SQL語句、返回結果集

下圖主要詳細描述了客戶端是如何連線到資料庫的:


訪問資料庫的程式碼一般都放在DAO(Data Assess Object 資料庫存取物件)層,DAO層位於業務邏輯和持久化資料之間,實現對持久化資料的訪問。DAO層起著轉換器的作用,把實體類轉換為資料庫中的記錄,或者把資料庫中的記錄轉換成實體類。

利用JDBC實現登入功能(程式碼):

登入頁面:login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>登入</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	<form action="login.action">
  		使用者名稱:<input type="text" name="uname" value="${param.uname }"><br/>
  		密碼:<input type="password" name="pwd" value="${param.pwd }"><br/>
  		<input type="submit" value="登入"><br/>
  		<span style="color: red;">${requestScope.error }</span>
  	</form>
  	<a href="register.jsp">沒有賬號,立即註冊</a>
  </body>
</html>

建立一個實體類:User.java

package com.jredu.entity;
/**
 * 實體類
 * @author Administrator
 *
 */
public class User {
	
	private int id;
	private String uname;
	private String pwd;
	
	public User() {
		super();
	}
	
	public User(String uname, String pwd) {
		super();
		this.uname = uname;
		this.pwd = pwd;
	}

	public User(int id, String uname, String pwd) {
		super();
		this.id = id;
		this.uname = uname;
		this.pwd = pwd;
	}


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public String getUname() {
		return uname;
	}


	public void setUname(String uname) {
		this.uname = uname;
	}


	public String getPwd() {
		return pwd;
	}


	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}


LoginServlet.java

package com.jredu.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jredu.entity.User;
import com.jredu.service.LoginService;
import com.jredu.service.impl.LoginServiceImpl;
@WebServlet(value="/login.action")
public class LoginServlet extends HttpServlet {
	
	private LoginService service;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uname=request.getParameter("uname");
		String pwd=request.getParameter("pwd");
		//呼叫javabean
		service=new LoginServiceImpl();
		User user=service.login(uname, pwd);
		//跳轉jsp
		if(user!=null) {
			request.getSession().setAttribute("user", user);
			response.sendRedirect("index.jsp");
		} else {
			request.setAttribute("error", "登入失敗請重新輸入");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		
	}

}

LoginService.java

package com.jredu.service;

import com.jredu.entity.User;

public interface LoginService {
	/**
	 * 登入功能
	 * @param uname
	 * @param pwd
	 * @return
	 */

	User login(String uname, String pwd);

}


LoginServiceImpl.java

package com.jredu.service.impl;

import com.jredu.dao.UserDao;
import com.jredu.dao.impl.UserDaoImpl;
import com.jredu.entity.User;
import com.jredu.service.LoginService;

public class LoginServiceImpl implements LoginService {

	private UserDao ud=new UserDaoImpl();
	@Override
	public User login(String uname, String pwd) {
		// TODO Auto-generated method stub
		//下面是業務處理,訪問資料庫在UserDaoImpl類中
		User user = new User(uname,pwd);
		return ud.findUser(user);
		
	}

}


UserDao.java

package com.jredu.dao;

import java.util.List;

import com.jredu.entity.User;
/**
 * 資料庫訪問的介面。
 * @author jiaxutianhuo
 *
 */
public interface UserDao {
	//登入
	User findUser(User user);
	
	//查詢
	public List<User> query(String sql,String sex) throws Exception;
}


UserDaoImpl.java

package com.jredu.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jredu.dao.UserDao;
import com.jredu.entity.User;
import com.jredu.util.BaseDao;


public class UserDaoImpl extends BaseDao implements UserDao {
	
	@Override
	public User findUser(User user) {
		// TODO Auto-generated method stub
		//3.執行sql語句
		//4.獲取結果集
		ResultSet rs=executeQuery("select * from users where username=? and userpwd=?", user.getUname(),user.getPwd());
		//訪問資料庫查詢是否存在該使用者
		try {
			//登入成功
			if(rs.next()) {
				//把結果集轉換成實體類
				user.setUname(rs.getString("username"));
				user.setPwd(rs.getString("userpwd"));
				user.setId(rs.getInt("userid"));
				return user;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll();
		}
		//不存在該使用者
		return null;
	}

	
	//查詢
	@Override
	public List<User> query(String sql, String sex) throws Exception {
		// TODO Auto-generated method stub
		List<User> list = new ArrayList<User>();
		ResultSet rs = new BaseDao().executeQuery(sql, sex);
		while (rs.next()) {
			User us = new User();
			us.setUname(rs.getString("name"));
			list.add(us);
		}
		return list;
	}

}


BaseDao.java

package com.jredu.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jredu.dao.UserDao;
import com.jredu.entity.User;
import com.jredu.util.BaseDao;


public class UserDaoImpl extends BaseDao implements UserDao {
	
	@Override
	public User findUser(User user) {
		// TODO Auto-generated method stub
		//3.執行sql語句
		//4.獲取結果集
		ResultSet rs=executeQuery("select * from users where username=? and userpwd=?", user.getUname(),user.getPwd());
		//訪問資料庫查詢是否存在該使用者
		try {
			//登入成功
			if(rs.next()) {
				//把結果集轉換成實體類
				user.setUname(rs.getString("username"));
				user.setPwd(rs.getString("userpwd"));
				user.setId(rs.getInt("userid"));
				return user;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll();
		}
		//不存在該使用者
		return null;
	}

	
	//查詢
	@Override
	public List<User> query(String sql, String sex) throws Exception {
		// TODO Auto-generated method stub
		List<User> list = new ArrayList<User>();
		ResultSet rs = new BaseDao().executeQuery(sql, sex);
		while (rs.next()) {
			User us = new User();
			us.setUname(rs.getString("name"));
			list.add(us);
		}
		return list;
	}

}


CharacterFilter.java

package com.jredu.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
 * 編碼過濾器
 * @author Administrator
 *
 */
@WebFilter(value="/*",initParams={@WebInitParam(name="encoding",value="utf-8")})
public class CharacterFilter implements Filter {

	private String encoding;
	
	/**
	 * 初始化
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("字元編碼過濾器啟動...");
		encoding=filterConfig.getInitParameter("encoding");
	}

	/**
	 * 過濾功能
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		//設定請求編碼格式
		request.setCharacterEncoding(encoding);
		//設定響應編碼格式
		response.setContentType("text/html;charset="+encoding);
		response.setCharacterEncoding(encoding);
		chain.doFilter(request, response);
	}
	
	/**
	 * 銷燬
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("字元編碼過濾器結束...");
	}

}


index.jsp

<%@ page language="java"
	import="java.util.*,com.jredu.util.BaseDao,java.sql.Connection,java.sql.ResultSet"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
</head>

<body>
	<%
		ResultSet rs = new BaseDao()
				.executeQuery("select * from users");
		while (rs.next()) {
	%>
	<%=rs.getString("USERNAME")%><br />
	<%
		}
	%>
</body>
</html>


上述程式碼執行的結果是:

用到的資料庫是:

什麼是JNDI:JNDI(Java Naming and Directory Interface,java命名和目錄介面),是一組在Java應用中訪問命名和目錄服務的API,通過名稱將資源與服務進行關聯。

使用連線池的好處:

1、可以彌補傳統資料庫連線方式的不足。傳統資料庫每一次請求時均需要連線資料庫,資源佔用較多;當併發訪問

資料量較大時,網站速度受到極大的影響;在訪問結束後必須要關閉連線釋放資源;系統的安全性和穩定性相對較差。

2、企業級開發需要穩健和高效的資料訪問層。使用連線池可以完成對資料庫的CRUD操作,能夠處理資料庫發生的各種錯誤,可以靈活的修改配置,提供方便使用的工具,具有的效能較高。

什麼是連線池技術:


連線池工作的原理:

利用連線池實現登入:

在上述程式碼的基礎上稍加修改,下面是修改了的程式碼:

UserDaoImpl.java

package com.jredu.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jredu.dao.UserDao;
import com.jredu.entity.User;
import com.jredu.util.BaseDao;
import com.jredu.util.JNDIBaseDao;


public class UserDaoImpl extends JNDIBaseDao implements UserDao {
	
	@Override
	public User findUser(User user) {
		// TODO Auto-generated method stub
		//3.執行sql語句
		//4.獲取結果集
		ResultSet rs=executeQuery("select * from users where username=? and userpwd=?", user.getUname(),user.getPwd());
		//訪問資料庫查詢是否存在該使用者
		try {
			//登入成功
			if(rs.next()) {
				//把結果集轉換成實體類
				user.setUname(rs.getString("username"));
				user.setPwd(rs.getString("userpwd"));
				user.setId(rs.getInt("userid"));
				return user;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll();
		}
		//不存在該使用者
		return null;
	}

	
	//查詢
	@Override
	public List<User> query(String sql, String sex) throws Exception {
		// TODO Auto-generated method stub
		List<User> list = new ArrayList<User>();
		ResultSet rs = new BaseDao().executeQuery(sql, sex);
		while (rs.next()) {
			User us = new User();
			us.setUname(rs.getString("name"));
			list.add(us);
		}
		return list;
	}

}

JNDIBaseDao.java

package com.jredu.util;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class JNDIBaseDao {

	private DataSource source; //資料來源
	private Connection connection;
	private PreparedStatement ps;
	private ResultSet rs;
	
	{
		try {
			Context ic = new InitialContext();//初始化
			source = (DataSource)ic.lookup("java:comp/env/jdbc/orcl");//在tomcat中配置
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void getConnection() {
		try {
			connection=source.getConnection();//資料來源建立connection
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 增刪改操作
	 * @param sql
	 * @param objs
	 * @return 影響行數
	 */
	public int executeUpdate(String sql,Object... objs) {
		if(connection==null) {
			getConnection();
		}
		int res=-1;
		try {
			//設定手動提交事務
			connection.setAutoCommit(false);
			connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
			ps=connection.prepareStatement(sql);
			if(objs!=null) {
				for(int i=0;i<objs.length;i++) {
					ps.setObject(i+1, objs[i]);
				}
			}
			res=ps.executeUpdate();
			//手動提交事務
			connection.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			if(ps!=null) {
				try {
					ps.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return res;
	}
	
	/**
	 * 查詢操作
	 * @param sql
	 * @param objs
	 * @return
	 */
	public ResultSet executeQuery(String sql,Object... objs) {
		if(connection==null) {
			getConnection();
		}
		try {
			ps=connection.prepareStatement(sql);
			if(objs!=null) {
				for(int i=0;i<objs.length;i++) {
					ps.setObject(i+1, objs[i]);
				}
			}
			rs=ps.executeQuery();
			return rs;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public void closeAll() {
		try {
			if(rs!=null) {
				rs.close();
			}
			if(ps!=null) {
				ps.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

index.jsp
<%@ page language="java"
	import="java.util.*,com.jredu.util.JNDIBaseDao,java.sql.Connection,java.sql.ResultSet"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
</head>

<body>
	<%
		ResultSet rs = new JNDIBaseDao()
				.executeQuery("select * from users");
		while (rs.next()) {
	%>
	<%=rs.getString("USERNAME")%><br />
	<%
		}
	%>
</body>
</html>

還需要在tomcat下的conf資料夾下的context.xml下加上:
<Resource name="jdbc/orcl" 
auth="Container" type="javax.sql.DataSource" maxTotal="100"  
maxIdle="30" maxWaitMillis="10000" username="zhao" password="Jredu12345" 
driverClassName="oracle.jdbc.driver.OracleDriver"  
url="jdbc:oracle:thin:@localhost:1521:orcl" />

相關推薦

Hibernate連線oracle資料庫:外部(遠端)資料庫內部(本地)資料庫

連線內部資料庫 <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>//127.0.0.0 <pr

在Linux下面使用Mysql的客戶端工具WorkBench建立資料庫使用者並連線

在這裡記一下怎麼用這個Workbench建立資料庫和使用者並連線。 首先,先說一個事,就是在客戶端中使用create database命令建立的“資料庫”(姑且叫它資料庫吧),在Workbench中,是叫Schema的,有點類似於oracle了;(莫非自己以前對Mysq

連結oracle urlDriver 及檢視Oracle資料庫有哪些

其中資料庫名預設為orcl,若想知道Oracle有哪些資料庫,可以檢視服務中service後面的名字有哪些 jdbc.user=c##foods jdbc.password=XXX jdbc.url=jdbc:oracle:thin:@localhos

mysql定時備份資料庫刪除N天前資料庫備份

前提,這裡使用 Ubuntu 16.04.4。 mysql定時備份數資料庫: 1.建立備份資料夾和指令碼檔案: mkdir -p /home/mysql_backup/ touch /home/mysql_backup/mysql_backup.sh 2.編輯指令碼檔案(m

讀excel圖片到資料庫上傳圖片到資料庫

//引用Excel名稱空間 using Excel; //...... //下面從test.xls中的2,2格複製圖片到剪貼簿,然後從剪貼簿讀取圖片並顯示到pictureBox1中。 private void btnGetImageFromExcel_Click(object

python2python3的區別 (附帶程式碼解析

1. input()函式 python2中的input()函式:獲取當前輸入的內容,並將其作為指令來處理 ; python3中的input()函式:獲取當前輸入的內容,並將其作為字串來處理; 在pytohn2環境中: 在輸入中文‘小花’的時候,會顯示語法

使用JDBC連線Oracle資料庫使用連線連線Oracle資料庫程式碼解析

這裡連線的是oracle資料庫。 JDBC是什麼:JDBC是java資料庫連線技術的簡稱,提供連線各種常用資料庫的能力。 客戶端傳送請求給應用伺服器,應用伺服器通過JDBC連線到資料庫伺服器,查詢資料庫中的資料,返回一個結果集,再把結果集轉換成實體類傳遞給客戶端。 JDBC

JavaWeb 之 15.JDBC提高(事物資料庫連線)

## 事務和資料庫連線池 ## **事務**          1.什麼是事務:一組邏輯上的操作,要麼全都成功,要麼全都失敗。     2.模擬事務的操作     &nb

JDBC資料庫的驅動、連線、java程式操作資料庫、事務、隔離級別、連線等)

java操作資料庫的思想:連上資料庫,傳送sql語句。在連上資料庫之前,要先用程式啟動資料庫,因此,可以通過反射載入類驅動(com.jdbc.mysql.Driver)。通過驅動管理類的靜態方法傳遞資料庫的url來獲取一個連線物件(connection)。有三個過載的方法,第一個user和p

JDBC資料庫連線連線資料庫資料庫操作DAO層設計通用更新及查詢方法(二)

上篇文章主要介紹了通過資料庫連線池連線資料庫,然後設計了對資料庫通用更新和查詢方法,本篇文章主要通過例項介紹上篇文章定義的對資料庫操作的幾個方法的使用:     首先我們先在資料庫建立一個學生資訊表Student欄位如圖: 建立好表將配置檔案的資訊改好然後需要建立一

JDBC資料庫連線連線資料庫資料庫操作DAO層設計通用更新及查詢方法(一)

該篇文章介紹了資料庫連線池獲取資料庫連線以及資料庫操作的基本使用,然後主要提供了java專案案例中dao層的一種設計,利用反射的原理定義了通用的查詢方法可以對應所有的表和例項。文章中的每段程式碼都提供了詳細的註釋及邏輯步驟 首先匯入資料庫連線的所需要的jar包:    

jdbc連線mysql資料庫(或oracle)驗證通過,並操作資料庫

1.連線資料庫其實很簡單,直接粘程式碼,首先我們先複製mysql的jar包 2.再建立資料庫連線資訊檔案,寫入檔案,DRIVER可以照抄,URL是本地的資料庫資訊,如果是伺服器的資料庫可以將localhsot改成伺服器Ip,使用者名稱和密碼是資料庫的。 3.建立一個db類,第一個

Oracle資料庫安裝+漢化版PLsql+Oracle外掛,plsql連線Oracle步驟報錯解決辦法

    從https://download.csdn.net/download/fxiaoyaole/10449523 此連結下載裡面有所資源,資源包括(Oracle兩個資料庫壓縮包win64_11gR2_database_1of2, win64_11gR2_database

JDBC連線資料庫查詢

/* JDBC工作過程: 1.載入驅動,建立連線(載入驅動是靠DriverManager,並且通過DriverManager獲取連線Connection) 2.建立語句物件(通過Connection建立Statement用於執行sql語句) 3.執行SQL語句 4.處理結

java 使用jdbc連線Greenplum資料庫Postgresql資料庫

1 public class JdbcUtils { 2 3 // 1、Postgresql 4 private static String postgresql_driver; 5 private static String postgresql_url;

連線資料庫(java驅動連線連線連線

使用java驅動連線資料庫:        String url ="jdbc:mysql://localhost:3306/zhongruan";        String usernam

JDBC —— 簡單的連線資料庫封裝

連線資料庫,並讀取表裡的內容 eclipse連線資料庫的一般過程是: 1,載入JDBC驅動(jar驅動包自己去下,這裡有匯入jar到eclipse的方法Eclipse下匯入外部jar包的3種方式) 2,建立資料庫連線(Connection介面) 3,建立

如何使用Oracle SQLDeveloper 中連線MS SQLServerMySQL資料庫(轉)

如何使用Oracle SQLDeveloper 中連線MS SQLServer和MySQL資料庫 一、連線至MySQL資料庫 1.下載mysql的jdbc驅動, [url]http://dev.mysql.com/downloads/[/url] 免費,嘿嘿。 2.解壓zip檔案(我下載

通過jdbc建立連線連線資料庫

一、匯入相關jar包 ojdbc14.jar(Oracle用的) 或 mysql-connector-java-5.1.17.jar(mysql用的)、jsonplugin-0.34.jar(業務中封裝資料用到,可生成json格式的資料)、commons-pool-1.5.

javaWeb實戰教程4-jdbc連線資料庫junit單元測試

javaWeb實戰教程 2.5 junit單元測試 我們在平時做程式碼時,每完成一個方法都需要先測試再提交,在java中比較常用的一個測試方法就是使用junit。 首先在專案中加入junit的jar包:junit-4.7.jar;將jar包複製到W