1. 程式人生 > >用java做網站,java連線資料庫並查詢輸出到頁面

用java做網站,java連線資料庫並查詢輸出到頁面

java web的字尾名是jsp,所以咱們要有一個jsp的開發環境,我這用的是jspStudy


自行百度。這軟體是一個整合開發環境,安裝啟動後即可使用,集成了tomcat和mysql資料庫

首先我們先新建一個首頁檔案

index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>mysql測試</title>

</head>
<body>

	<%
			 //此進行連線資料庫
		    String url="jdbc:mysql://127.0.0.1:3306/test"; //test為資料庫名稱
		    String dbuser="root"; //資料庫賬戶
			String dbpwd="root"; //資料庫密碼
			try 
			{
				Class.forName("com.mysql.jdbc.Driver"); //載入驅動 JspStudy
			} 
			catch (ClassNotFoundException e) 
			{ 
				e.printStackTrace();
			}  
			//取得資料庫連線conn
			Connection conn=DriverManager.getConnection(url, dbuser, dbpwd);;

			PreparedStatement ps=null;
			ResultSet rs=null;
			//宣告資料庫欄位
			String id="";
			String title="";
			String img="";
			try 
			{ 
				String sql="select * from res";
				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();
				while(rs.next())
				{
					id=rs.getString(1);
					title=rs.getString(2);
					img=rs.getString(3);
					out.println("ID:"+id+"<br>");
					out.println(title+"<br><br>"); 
					out.println("<img src=\""+img+"\"/>"+"<br><br>"); 
				}
			}
			catch (SQLException e) 
			{
				e.printStackTrace();
			}
			finally
			{ 
					try 
					{
						if(rs!=null)			
							rs.close();
					} 
					catch (SQLException e) 
					{
						e.printStackTrace();
					}
					finally
					{
							try 
							{
								if(ps!=null)					
									ps.close();
							} 
							catch (SQLException e) 
							{ 
								e.printStackTrace();
							}
							finally
							{
								try 
								{
									if(conn!=null)					
										conn.close();
								} 
								catch (SQLException e) 
								{ 
										e.printStackTrace();
								}
							}
					}
			} 
	%>		
</body>
</html>

然後拷貝到jspStudy的WWW目錄
在瀏覽器輸入http://localhost/index.jsp
即可執行。

當然資料庫的資料要有

這是我這邊資料庫的結構


最終效果: