jsp连接MySQL数据库

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

jsp连接MySQL数据库_第1张图片

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="java.sql.*" %>


  
  


<%! 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()){
%>
价格:<%=rs.getString("prices")%> <%=rs.getString("cnames")%>
<%=rs.getString("cids")%>
<% } %>

jsp连接MySQL数据库_第2张图片

 

jsp连接MySQL数据库_第3张图片

 

你可能感兴趣的:(java,数据库,mysql)