Table of Contents
1. Create database
2. Create a web Project
3. Running results
Home Java javaTutorial java_web learning-display data in mysql

java_web learning-display data in mysql

Jun 26, 2017 am 10:41 AM
java mysql web study show

1. Create database

create database animal;

create table animal(

sno int,

name varchar(20),

weight varcahr(20),

color varchar(20),

birth date

);

Insert data

insert into animal values('1','lion','200kg','yellow','2014-07-30'),('3','tiger','180kg','yellow',' 2010-02-14'),('2','monkey','20kg','brown','2003-04-14'),('6','elephant','1000kg','black ','2009-07-12'),('5','giraffe','700kg','yellow','2007-07-13');

As shown in the picture:

2. Create a web Project

Import five packages in the lib folder:

The project name is: Animal1

There are three packages in the project: entity, action, util

A jsp File: An.jsp

Code in ConnManager.java

 1 package util; 2  3 import java.sql.Connection; 4 import java.sql.DriverManager; 5  6 public class ConnManager { 7  8     //数据库5大参数 9     private static final String IP = "127.0.0.1";10     private static final String PORT = "3306";11     private static final String DATABASE_NAME = "zhz";12     private static final String USER_NAME = "root";13     private static final String PASSWORD = "";14     private static final String DRIVER = "org.gjt.mm.mysql.Driver";15     16     public static Connection getConnection() throws Exception {17         String url = "jdbc:mysql://"+IP+":"+PORT+"/"+DATABASE_NAME+"?user="+USER_NAME+"&password="+PASSWORD+"";18         Class.forName(DRIVER);19         Connection conn = DriverManager.getConnection(url);20         return conn;21     }22 23 }
Copy after login

Code in Pig.java Code

 1 package entity; 2  3 import java.util.Date; 4  5 public class Pig { 6     private Integer id=null; 7     private String name=null; 8     private String weight=null; 9     private String color=null;10     private Date birth=null;11     public Integer getId() {12         return id;13     }14     public void setId(Integer id) {15         this.id = id;16     }17     public String getName() {18         return name;19     }20     public void setName(String name) {21         this.name = name;22     }23     public String getWeight() {24         return weight;25     }26     public void setWeight(String weigth) {27         this.weight = weigth;28     }29     public String getColor() {30         return color;31     }32     public void setColor(String color) {33         this.color = color;34     }35     public Date getBirth() {36         return birth;37     }38     public void setBirth(Date birth) {39         this.birth = birth;40     }41     42 }
Copy after login

Code in showPig.java

 1 package action; 2  3 import java.io.IOException; 4 import java.sql.Connection; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 import javax.servlet.ServletException;11 import javax.servlet.annotation.WebServlet;12 import javax.servlet.http.HttpServlet;13 import javax.servlet.http.HttpServletRequest;14 import javax.servlet.http.HttpServletResponse;15 16 import entity.Pig;17 import util.ConnManager;18 19 @WebServlet("/showPig")20 public class showPig extends HttpServlet {21     private static final long serialVersionUID = 1L;22       23    24     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {25         try {26             Connection conn = ConnManager.getConnection();27             String sql = "select * from animal";28             PreparedStatement ps = conn.prepareStatement(sql);29             //建立一个池,用于存放数据30             List<Pig> pigList = new ArrayList<Pig>();31             ResultSet rs = ps.executeQuery();32             while(rs.next()){34                 Integer id = rs.getInt("id");35                 String name = rs.getString("name");36                 String weight = rs.getString("weight");37                 String color = rs.getString("color");38                 java.sql.Date birth= rs.getDate("birth");39                 Pig s = new Pig();40                 s.setId(id);41                 s.setName(name);42                 s.setWeight(weight);43                 s.setColor(color);44                 s.setBirth(birth);45                 pigList.add(s);46             }47             rs.close();48             ps.close();49             conn.close();50             request.setAttribute("pigList", pigList);51             request.getRequestDispatcher("An.jsp").forward(request, response);52             53         } catch (Exception e) {54             System.out.println("发生异常"+e.getMessage());55         }56     }57 58     59     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {60         61         doGet(request, response);62     }63 64 }
Copy after login

Code in An.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%> 4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%> 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>Insert title here</title>10 </head>11 <body>12 <table border = "2px" width = "80%">13     <tr>14         <td>编号</td>15         <td>名字</td>16         <td>体重</td>17         <td>颜色</td>18         <td>入园日期</td>19     </tr>20     <c:forEach var="L" items="${pigList}">21     <tr>22         <td>${L.id }</td>23         <td>${L.name }</td>24         <td>${L.weight }</td>25         <td>${L.color }</td>26         <td><fmt:formatDate value="${L.birth }" pattern="yyyy-MM-dd"></fmt:formatDate></td>27     </tr>28     </c:forEach>29 </table>30 </body>31 </html>
Copy after login

3. Running results

Run the Servlet, the running results are as shown in the figure:

The above is the detailed content of java_web learning-display data in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

See all articles