閑來無事,學學java,雖說編程語言相通,但是接觸一門新知識還是有些疑惑,邊學邊記錄,方便以后溫故。
直接給出代碼:
1 <%@page import="java.sql.ResultSet"%> 2 <%@page import="com.mysql.jdbc.Statement"%> 3 <%@page import="java.sql.DriverManager"%> 4 <%@page import="com.mysql.jdbc.Connection"%> 5 <%@ page language="java" contentType="text/html; charset=gbk" 6 pageEncoding="gbk"%> 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 8 <html> 9 <head> 10 <meta http-equiv="Content-Type" content="text/html; charset=gbk"> 11 <title>Insert title here</title> 12 </head> 13 <body> 14 <% 15 //加載驅動 16 Class.forName("com.mysql.jdbc.Driver"); 17 //建立連接 18 Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/house", "root", 19 "123456"); 20 //創建Statement 21 Statement stm = (Statement) conn.createStatement(); 22 //執行查詢 23 ResultSet rs = stm.executeQuery("select username,pwd from user"); 24 %> 25 <table border="1" width="300"> 26 <% 27 //遍歷結果 28 while (rs.next()) { 29 %> 30 <tr> 31 <td><%=rs.getString(1)%></td> 32 <td><%=rs.getString(2)%></td> 33 </tr> 34 <% 35 } 36 %> 37 </table> 38 </body> 39 </html>
要把mysql驅動包放入項目的WEB-INF/lib下面。剛開始寫時候沒有對Connection和Statement進行強制轉換,老是有紅色××,所以要注意注意。