SQL --------JDBC 用用戶名查詢用戶的信息


package demo;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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 Edit
 */
@WebServlet("/found.do")
public class found extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public found() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		//獲取用來查詢記錄的參數
		String name = request.getParameter("name");
		System.out.println(name);

		//設置數據庫連接參數
		String url = "jdbc:mysql://localhost:3306/庫名?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT";
		String user = "用戶名";
		String password = "密碼";

		//加載數據庫驅動
		try {
			Class.forName("com.mysql.jdbc.Driver");// 加載數據庫的JDBC驅動程序
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		Customer customer = new Customer();

		try (Connection connection = DriverManager.getConnection(url, user, password)) {//連接數據庫

			//設置sql語句,查詢CustomerName為name的記錄的數據,customers為表名
			String sql = "SELECT*FROM customers where CustomerName= ? ";
			PreparedStatement statement = connection.prepareStatement(sql);
			
			statement.setString(1, name);
			ResultSet rs = statement.executeQuery();

			while (rs.next()) {
				// 將數據庫的數據轉換成POJO實例
				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"));

			} 
			
			rs.close();
			statement.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		request.setAttribute("customer", customer);//將獲取到的參數封裝成對象傳遞到查找到得記錄的界面
		request.getRequestDispatcher("showone.jsp").forward(request, response);
	}

}

 


免責聲明!

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



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