Example :  JSP and Select Menu/DropDownList from Database (Java)       | 
   
 
			  
			  
                Example :  JSP and Select Menu/DropDownList from Database (Java) ตัวอย่างการเขียน JSP เพื่อติดต่อกับ Database  และการอ่านข้อมูลจาก Database มาแสดงใน List Menu /DropDownList โดยใช้การ Loop ข้อมูลใน Item ของ Select Menu 
 
Example ตัวอย่างการเขียน JSP  เพื่ออ่านข้อมูลจาก Database มาแสดงใน List menu / DropDownList 
 
  
 
เนื่องจากใช้ Database ของ MySQL จึงเลือกใช้ MySQL Connector ด้วยการเรียกไฟล์ jar 
 
mysql 
CREATE TABLE `customer` (
  `CustomerID` varchar(4) NOT NULL,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `CountryCode` varchar(2) NOT NULL,
  `Budget` double NOT NULL,
  `Used` double NOT NULL,
  PRIMARY KEY  (`CustomerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- 
-- dump ตาราง `customer`
-- 
INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John  Smith', '[email protected]', 'UK', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);
INSERT INTO `customer` VALUES ('C005', 'Chai Surachai', '[email protected]', 'TH', 5000000, 0);
 
โครงสร้างของ Table และ Data 
 
  
 
ฐานข้อมูลของ MySQL 
 
index.jsp 
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<html>
<head>
	<title>ThaiCreate.Com JSP Tutorial</title>
</head>
<body>
	
	<%
	Connection connect = null;
	Statement s = null;
	
	try {
		Class.forName("com.mysql.jdbc.Driver");
		
		connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
				"?user=root&password=root");
		
		s = connect.createStatement();
		
		String sql = "SELECT * FROM  customer ORDER BY CustomerID ASC";
		
		ResultSet rec = s.executeQuery(sql);
		%>
		
		  <select name="selectMenu">
			<%while((rec!=null) && (rec.next())) { %>
			<option value="<%=rec.getString("CustomerID")%>"><%=rec.getString("Name")%></option>
			<%}%>
		  </select>		
	     
	    <%	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.println(e.getMessage());
			e.printStackTrace();
		}
	
		try {
			if(s!=null){
				s.close();
				connect.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			out.println(e.getMessage());
			e.printStackTrace();
		}
	%>
</body>
</html>
 
Output 
 
  
 
แสดงข้อมูลจาก Database ใน Select Menu / DropDownList 
 
 
อ่านเพิ่มเติมเกี่ยวกับ JSP และการติดต่อกับ Database ต่าง ๆ  
              
  
              			
			  
								  
			  
  
                          
  |