jsp连接mysql案例

下载mysql-connector-java-5.1.26

将mysql-connector-java-5.1.26-bin.jar放在\jdk\jre\lib\ext中


------------------------------------------------------


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
</head>
<body>
<%
	Connection con;
	Statement sql;
	ResultSet rs;
	String url;
	try{
		Class.forName("com.mysql.jdbc.Driver");
		}
	catch(Exception e){
		out.print(e);
		}
	
	try{
	    url = "jdbc:mysql://localhost:3306/weather";
	    con = DriverManager.getConnection(url,"root","lgh123");
	    sql = con.createStatement();
	    rs = sql.executeQuery("SELECT * FROM weather");
	    out.print("<table border=2>");
	    out.print("<tr>");
	    out.print("<th width=100>"+"city");
	    out.print("<th width=100>"+"city_code");

	    out.print("</tr>");
	    while(rs.next()){
	        out.print("<tr>");
	        out.print("<td>"+rs.getString(2)+"</td>");
	        out.print("<td>"+rs.getString(1)+"</td>");
	        out.print("</tr>");
	    }
	    out.print("</table>");
	    con.close();
	}
	catch(SQLException f){
		out.print(f);
		}
%>
</body>
</html>
jsp连接mysql案例_第1张图片

你可能感兴趣的:(jsp连接mysql案例)