1. 程式人生 > >JSP | 使用純JAVA驅動連線MySQL資料庫

JSP | 使用純JAVA驅動連線MySQL資料庫

本程式採用的整合開發環境是eclipse。

採用的資料庫是JspStudy裡整合的MySQL資料庫。

MySQL的java連線驅動在jspstudy的安裝目錄下Tomcat——>lib資料夾下:


沒有安裝jspstudy的話,mysql的java驅動可以在官網下載:https://dev.mysql.com/downloads/connector/

本程式使用eclipse佈置web工程時,需要將此驅動佈置在webcontent——>WEB-INF——>lib目錄下。

這是mysql資料庫裡進行測試的資料庫text下的users表,接下來對其進行來連線測試。


測試程式:

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%@ page import="java.sql.*"%>
<html>
<head>
<title>useMySQL.jsp</title>
</head>
<body bgcolor="lightblue">
	<%
		Connection con = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
			st=con.createStatement();
			rs=st.executeQuery("select * from users");
			out.print("<table border=1>");
			out.print("<tr>");
				out.print("<th>id</th>");
				out.print("<th>username</th>");
				out.print("<th>password</th>");
				out.print("<th>name</th>");
			out.print("</tr>");
			while(rs.next()){
				out.print("<tr>");
					out.print("<td>"+rs.getString(1)+"</td>");
					out.print("<td>"+rs.getString(2)+"</td>");
					out.print("<td>"+rs.getString(3)+"</td>");
					out.print("<td>"+rs.getString(4)+"</td>");
				out.print("</tr>");
			}
			out.print("</table>");
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try{
				if(rs!=null){
					rs.close();
				}
				if(st!=null){
					st.close();
				}
				if(con!=null){
					con.close();
				}
			}catch (SQLException e) {
				e.printStackTrace();
			}
		}
	%>
</body>
</html> 

測試結果如下: