1.jdbc连接数据库步骤
1)导入数据库jar包
2)注册驱动Class.forName("com.mysql.jdbc. Driver");
3)创建连接
String url="jdbc:mysql://localhost:3306/数据库名";
String user="root";//用户名
String pwd="root";//密码
Connection con=DriverManager.getConnection(url,user,pwd);
4)创建执行对象
Statement stmt = con.createStatement();
5)操作数据库
String sql = "select * from 表名 where 1 = 1";
if (cids!= null && !cids.equals("")){
sql += " and cids = '" + cids + "'";
}
if (cnames != null && !cnames.equals("")){
sql += " and name like '%" + cnames + "%'";
}
if (prices != null && !prices.equals("")){
sql += " and prices like '%" + prices + "%'";
}
System.out.println(sql); rs = stmt.executeQuery(sql);
6)前端显示
<%=rs.getString("prices")%>
2.实例
数据库名:jdbc
表名:newfiledata
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@page import="java.sql.*" %> <head> <title></title> <style type="text/css"> .item{ float:left; border: solid 1px gray; margin-right:60px; margin-bottom:25px; } .item:hover{ border: solid 1px orange; box-shadow: 5px 5px 5px gray; } .item div{ margin: 14px; line-height: 25px; } .item div>span:nth-child(3){ color: red; } .item div span:last-child{ color: gray; } .item div input{ float: right; } </style> </head> <body bgcolor="#2f4f4f"> <%! ResultSet rs;%> <% request.setCharacterEncoding("utf-8"); String cids = request.getParameter("cids"); String cnames = request.getParameter("cnames"); String prices = request.getParameter("prices"); Class.forName("com.mysql.cj.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC"; String user="root"; String pwd="root"; Connection conn= DriverManager.getConnection(url,user,pwd); Statement stmt = conn.createStatement(); String sql = "select * from newfiledata where 1 = 1 "; if (cids != null && !cids.equals("")){ sql += " and cids = '" + cids + "'"; } if (cnames != null && !cnames.equals("")){ sql += " and name like '%" + cnames + "%'"; } if (prices != null && !prices.equals("")){ sql += " and prices like '%" + prices + "%'"; } System.out.println(sql); rs = stmt.executeQuery(sql); %> <% while (rs.next()){ %> <table class="item" style="position: relative; left: 240px; width: 250px"> <td style="width: 15px">价格:<span style="color: red;"><%=rs.getString("prices")%></span></td> <td><%=rs.getString("cnames")%><br></td> <td><%=rs.getString("cids")%><input type="button" οnclick="return confirm('已加入购物车!')" value="购买"></td> </table> <% } %> </body> </html>