Queries to implement a database in a JSP page are mainly connected to the Java Code section of the database and the HTML page Code section. To implement this page, we go through a three-step
1, write the code to connect the database
2, write the code to display the page
3, the code to connect the database into the appropriate location of the page code.
1. Code to connect to the database
1.1 Import SQL Package <% import= "java.sql.*"%>
1.2 connecting, querying, shutting down the database
How to see if there are any elephants in the fridge. 1, open the refrigerator door. 2, take a look. 3, close the refrigerator door. This is the process .....
<%
class.forname ("Com.mysql.jdbc.Driver"). newinstance ();
String url= "Jdbc:mysql://localhost:3306/news";
String user= "root";
String password= "1234";
Configure and connect
the database Connection conn = drivermanager.getconnection (URL, user, password);
Statement st = Conn.createstatement ();
Query statements that display the last 10 and in reverse order
ResultSet rs = st.executequery ("SELECT * from data ordered by ID DESC LIMIT");
Output header
out.println ("<tr><td> title </td><td> content </td><td> Time </td></ Tr> ");
Output the results of each query sequentially
(Rs.next ()) {
out.print ("<tr><td>" +rs.getstring ("title") + "</td> <td> "+rs.getstring" ("content") + "</td><td>" +rs.getstring ("date") + "</td></tr><br > ");
If you use a column name, enclose the quotation mark
}
out.print ("</table>
2. HTML code for the page
To make the page beautiful, do a little landscaping ~ to make a table to store data
<%@ page language= "java" import= "java.util.*, java.sql.*" pageencoding= "gb2312"%> <% String Path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <%request.setcharacterencoding ("UTF-8");%> <%response.setcharacterencoding ("UTF-8");%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
3. Put the previous two code together
Note the placement of the code when you put it.
<%@ page language= "java" import= "java.util.*, java.sql.*" pageencoding= "gb2312"%> <% String Path =
Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <%request.setcharacterencoding ("UTF-8");%> <%response.setcharacterencoding ("UTF-8");%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">