<%@ 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.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//此进行连接数据库
String url="jdbc:mysql://localhost:3306/lcz?characterEncoding=utf-8&rewriteBatchedStatement=true"; //test为数据库名称
String user="root"; //数据库账户
String password="root"; //数据库密码
try
{
Class.forName("com.mysql.cj.jdbc.Driver"); //加载驱动 Jsp
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
//取得数据库连接conn
Connection conn=DriverManager.getConnection(url, user, password);;
PreparedStatement ps=null;
ResultSet rs=null;
//声明数据库字段
String id="";
String title="";
String img="";
try
{
String sql="select * from test2";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next())
{
id=rs.getString("id");
title=rs.getString("title");
img=rs.getString("img");
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>
网友评论