JAVA數據庫連接

這段時間在學習JAVA WEB,記錄一些數據庫連接語句,以防文件丟失等等,以供參考

第一種方式連接:JDBC,使用JDBC前提要創建lib文件夾,把jar文件放入其中,再build path就可以用了

try {
	//1 註冊驅動,爲固定代碼
	Class.forName("com.mysql.jdbc.Driver");
	//2 獲得鏈接,此處可設置服務器端口和選擇數據庫,以及數據庫賬號和密碼
	Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/group2","root","root");
	//3 獲得語句執行者
	Statement st = conn.createStatement();
	//4 執行語句
	ResultSet rs = st.executeQuery("select * from classinfo");
	//5 輸出結果
	while(rs.next()) {
		int user_id = rs.getInt("ID"); //通過列名獲得值
		String user_name = rs.getString("COLLEGE");
		System.out.print(user_id+ " : " + user_name+"\n");
	}
	//6 釋放資源
	rs.close();
}catch(Exception ex) {
			
}

第二種方式是使用DataSource連接數據庫,注:此處會創建多個文件,其中會註釋每個步驟的含義

1.此處用的是配置文件連接方式。在src路徑下創建c3p0-config.xml,名字必須爲這個

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="user">root</property>
		<property name="password">root</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
        <!-- 設置端口號和選擇數據庫 -->
		<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/web13</property>
		<!-- 初始化池大小 -->
        <property name="initialPoolSize">2</property>
        <!-- 最大空閒時間 -->
        <property name="maxIdleTime">30</property>
        <!-- 最多有多少個連接 -->
        <property name="maxPoolSize">10</property>
        <!-- 最少幾個連接 -->
        <property name="minPoolSize">2</property>
        <!-- 每次最多可以執行多少個批處理語句 -->
        <property name="maxStatements">50</property>
	</default-config> 
</c3p0-config> 

2.創建DataSourceUtils.java文件,類名以及包名看下面,

package com.itheima.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

	private static DataSource dataSource = new ComboPooledDataSource();
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	//threadlocal而是一個線程內部的存儲類,可以在指定線程內存儲數據,數據存儲以後,只有指定線程可以得到存儲數據
	// 直接可以獲取一個連接池
	public static DataSource getDataSource() {
		return dataSource;
	}
	
	// 獲取連接對象
	public static Connection getConnection() throws SQLException {
		Connection con = tl.get();
		if (con == null) {
			con = dataSource.getConnection();
			tl.set(con);
		}
		return con;
	}

	// 開啓事務
	public static void startTransaction() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.setAutoCommit(false);
		}
	}

	// 事務回滾
	public static void rollback() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.rollback();
		}
	}

	// 提交併且 關閉資源及從ThreadLocall中釋放
	public static void commitAndRelease() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.commit(); // 事務提交
			con.close();// 關閉資源
			tl.remove();// 從線程綁定中移除
		}
	}

	// 關閉資源方法
	public static void closeConnection() throws SQLException {
		Connection con = getConnection();
		if (con != null) {
			con.close();
		}
	}

	public static void closeStatement(Statement st) throws SQLException {
		if (st != null) {
			st.close();
		}
	}

	public static void closeResultSet(ResultSet rs) throws SQLException {
		if (rs != null) {
			rs.close();
		}
	}

}

3.創建LoginServlet.java文件,此處我測試的功能是驗證用戶名和密碼是否正確

package com.itheima.login;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.itheima.domain.User;
import com.itheima.utils.DataSourceUtils;

public class LoginServlet extends HttpServlet {
	
	@Override
	public void init() throws ServletException {
		//在Seveltcontext域中存一個數據count
		int count = 0;
		this.getServletContext().setAttribute("count", count);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//1、獲得用戶名和密碼
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//2、從數據庫中驗證該用戶名和密碼是否正確
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from user where username=? and password=?";
		User user = null;
		try {
			user = runner.query(sql, new BeanHandler<User>(User.class), username,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//3、根據返回的結果給用戶不同顯示信息
		if(user!=null){
			//從servletcontext中取出count進行++運算
			ServletContext context = this.getServletContext();
			Integer count = (Integer) context.getAttribute("count");
			count++;
			//用戶登錄成功
			response.getWriter().write(user.toString()+"---you are success login person :"+count);
			context.setAttribute("count", count);
		}else{
			//用戶登錄失敗
			response.getWriter().write("sorry your username or password is wrong");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

PS:後臺處理邏輯基本就這樣,這裏來捋一捋ComboPooledDataSource用配置文件連接數據庫的思路

1.在src下創建c3p0-config.xml文件,填寫數據庫的賬戶和密碼

2.

 ComboPooledDataSource pool = new ComboPooledDataSource();
//空參,自動到classpath目錄下面加載“c3p0-config.xml”配置文件---配置文件的存儲位置和名稱必須是這樣,且使用“默認配置”

上面用了封裝,邏輯會比較繞一點,後續再有深入學習或是新的理解會補充更新

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