前提条件:
1.安装Java,tomcat,MySQL,eclipse
2.配置java 环境变量
3.配置MySQL参数
4.tomcat能正常启动
使用eclipse编写代码:
1. 新建一个web project. 选择“Dynamic Web Project”. 按提示往下继续进行。
2. 工程建立完成后,在Webcontent目录下,右键new->jsp file
3. 输入jsp代码如下:
<%@page import="java.sql.SQLException" import="java.sql.ResultSet" import="java.sql.Statement"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Test mysql connectivity</title>
</head>
<body>
<%
java.sql.Connection conn;
java.lang.String strConn;
conn=null;
//Connect to the database
Class.forName("com.mysql.jdbc.Driver").newInstance();
try
{
conn=java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/new_schema?useSSL=false","root","wen_201611!");
} catch (SQLException e)
{
System.out.println(e.getMessage());
}
//Connnect success, then query the data from table1, and display the content in page
if (conn!=null)
{
out.println("database connect success");
Statement stmt=null;
ResultSet rs=null;
try {
stmt=conn.createStatement();
rs=stmt.executeQuery("SELECT * FROM table1");
while (rs.next())
{
%>
<p>The value of row <%=rs.getRow()%> col 1 is <%=rs.getInt(1)%></p>
<p>The value of row <%=rs.getRow()%> col 2 is <%=rs.getString(2)%></p>
<%
}
} catch (SQLException ex)
{
System.out.println("SQLException: "+ex.getMessage());
System.out.println("SQLState: "+ex.getSQLState());
System.out.println("VendorError: "+ex.getErrorCode());
}
//release resources
finally
{
if (rs!=null)
{
try{
rs.close();
System.out.println("\nrs destoryed");
} catch (SQLException sqlEx) {}
rs=null;
}
if (stmt!=null)
{
try{
stmt.close();
System.out.println("stmt destoryed");
} catch (SQLException sqlEx){}
stmt=null;
}
}
}
else
out.println("database connect failed");
%>
</body>
</html>
4. 点击eclipse的运行按钮,可以运行该jsp页面。
注意事项:
遇到无法找到jdbc类的异常的话,将jdbc connecter 拷贝到tomcat安装目录下的lib目录下。