SQL -------- JDBC 查詢所有記錄


package demo;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

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

/**
 * Servlet implementation class Queryalldata
 */
@WebServlet("/queryalldata.jsp")
public class Queryalldata extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Queryalldata() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//查詢所有數據
		
		//設置數據庫連接參數
		String url="jdbc:mysql://localhost:3306/庫名?serverTimezone=UTC";
		String user="用戶名";
		String password="密碼";
		
		//加載數據庫驅動
		try {
			Class.forName("com.mysql.jdbc.Driver");//加載數據庫的JDBC驅動程序
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		List<Customer> list = new ArrayList<Customer>();//初始化一個Customer線性列表
		
		try(Connection connection=DriverManager.getConnection(url, user, password)){//連接數據庫
			Statement statement = connection.createStatement();
			String sql="SELECT*FROM customers";//查詢所有數據的sql語句,customers為表名
			ResultSet rs=statement.executeQuery(sql);
			
			//遍歷數據庫所有數據,並添加到列表list中
			while(rs.next()) {
				Customer customer = new Customer();
				customer.setCustomerID(rs.getInt("CustomerID"));
				customer.setCustomerName(rs.getString("CustomerName"));
				customer.setContactName(rs.getString("ContactName"));
				customer.setAddress(rs.getString("Address"));
				customer.setCity(rs.getString("City"));
				customer.setPostalCode(rs.getString("PostalCode"));
				customer.setCountry(rs.getString("Country"));
				list.add(customer);
			}
			
			rs.close();
			statement.close();
			
		}catch(SQLException e) {
			e.printStackTrace();
		}
		
		String msg =(String) request.getAttribute("msg");
		if(msg!=null || msg !=" ")
			request.setAttribute("msg", msg);
		
		//將有數據的列表傳遞到顯示記錄所有界面
		request.setAttribute("customers", list);
		request.getRequestDispatcher("all.jsp").forward(request, response);
	}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM