前提条件:
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代码如下:
pageEncoding="ISO-8859-1"%>
Test mysql connectivityjava.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())
{
%>
The value of row col 1 is
The value of row col 2 is
}
} 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");
%>
4. 点击eclipse的运行按钮,可以运行该jsp页面。
注意事项:
遇到无法找到jdbc类的异常的话,将jdbc connecter 拷贝到tomcat安装目录下的lib目录下。