table of Contents
1. The purpose and requirements of the experiment
Use java language to query the data of one of the tables from the MySQL database.
2. Experimental environment
Windows 10 environment
java version: 11.0.10
IDE tool: IntelliJ IDEA 2020.3
MySQL: 5.7.26
3. Experimental content
Download tomcat
First download Tomcat in Windows. The steps are as follows:
-
Go to the official website to download, I downloaded tomcat 8.
-
Download and unzip to the directory you want to place, then open the command line (win+R, cmd), enter the disk where the file is located, cd, copy and paste the bin folder path.
-
Enter service.bat install in the bin to install. Tip: The service'Tomcat8' has been installed. It means the installation is successful.
-
After the installation is complete, configure the system environment variables (in the right-click properties of my computer)
-
The bin path and lib path are added to the path system variable.
-
Run startup.bat, garbled characters (see the experiment summary below for garbled solutions)
-
So far Tomcat is successful
Download mysql driver
Create a user sa in the mysql database and set the password to 123456, and please create a test database in advance, in which a hello table is created as follows: id is self-increasing as the primary key.
-
Enter the pipe network , select the operating system and enter the download page.
-
Then you will be asked to log in (if you don't have an account, just apply for one), just fill in some information after logging in to your account. Download after submission.
-
This compressed package contains the mysql-connector-java-8.0.23.jar file (this driver is downward compatible with all versions)
Configure IDEA
-
Copy the downloaded mysql-driven jar file to the lib library folder of tomcat. (Not necessary this time, I may use it in the future)
-
Create a java web project (see the experiment summary for those that cannot be created directly)
-
Configure Tomcat.
Click Run—EDit Configurations...
Click the "+" sign on the left, find Tomcat Server—Local and click, and then configure as shown in the figure (if not found, click the Templates configuration as shown in the figure, and then click the warning above! Create configuration) -
Create two folders under WEB-INF under the web directory of the project, one is classes, which is used to save the files compiled when the program is running. The other is the lib folder, which is used to store the external classes to be stored when the program is running.
-
Next, configure the project structure and tomcat.
In the file menu, click Project Structure...
The out path selects the classes folder just now.
The reference path of the external classes selects the lib folder just created. (After selecting the pop-up selection box, select Jar directory) The
Tomcat experiment needs to be selected in the Library
-
Put the downloaded jdbc driver package into the lib folder just created.
-
Create your own packages and classes in the src folder. (Same as java se)
-
Create a File file under the src folder and name it DBConfig.properties. The information in the file is shown in the figure. (This is not necessary. You can also put the information in the file in the class. But the advantage of this is that even if you change the database, you only need to modify the information in the configuration file, without having to change the class.)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
user=sa
psd=123456
//旧版本的连接
//driver=com.mysql.jdbc.Driver
//url=jdbc:mysql//localhost:3306/test
//user=sa
//psd=123456
- Edit to get the database connection function
package com.liupanlong.readMysql;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class connectMysql {
public Connection getConnection(){
String driver = null;
String url = null;
String user = null;
String psd = null;
Connection conn = null;
Properties pro = new Properties(); //新建一个properties实例,用于从DBConfig中拿到连接参数。
try {
pro.load(this.getClass().getClassLoader().getResourceAsStream("DBConfig.properties")); //加载DBConfig文件。
driver = pro.getProperty("driver");
url = pro.getProperty("url");
user = pro.getProperty("user");
psd = pro.getProperty("psd");
} catch (IOException e) {
e.printStackTrace();
}
try {
Class.forName(driver); //加载jdbc驱动
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url,user,psd); //获取数据库连接
conn.setAutoCommit(false);
return conn; //返回一个数据库连接。
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
- Create a test class to test whether the connection can be obtained.
package com.liupanlong.readMysql;
import java.sql.Connection;
public class Test {
public static void main(String[] args){
connectMysql open = new connectMysql();
Connection conn = open.getConnection();
System.out.println(conn);
}
}
Right-click in the blank space to run.
11. Create the index.jsp file under the web folder, add the <h1>我爱北京天安门!<h1>
code to the tag
12. Then select the run configured above and click the triangle to run.
13. Log in in the browser and http://localhost:8080/web/index.jsp
you can see I love Beijing Tiananmen Square
Start experiment
After completing the above steps, congratulations to your environment is finally set up, you can start the experiment.
If there is a pursuit, you can achieve the simplest front-end separation (I think it is feasible but I have not learned, you can make a private message or leave a message in the comment area)
- Add a class Hello_table to the package
package com.liupanlong.readMysql;
public class Hello_table {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Hello_table(int id, String name) {
this.id = id;
this.name = name;
}
}
2. Modify the code of readhello
package com.liupanlong.readMysql;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class readhello {
public List readFirstHello() throws SQLException {
List<Hello_table> list =new ArrayList<Hello_table>();
connectMysql open = new connectMysql();
Connection con = open.getConnection(); //连接类
//然后创建statement类对象,用来执行SQL语句
Statement statement=con.createStatement(); //Statement实现增删改查
//你要执行的Sql语句
String sql="select id,name from hello";
//最后设置Resultset类,用来存放获取的 结果集
ResultSet rs=statement.executeQuery(sql); //结果集
int Id=0;
String name=null;
while(rs.next()) {
Id = rs.getInt("id");
name=rs.getString("name");
Hello_table tl=new Hello_table(Id, name);
list.add(tl);
}
//最后关闭
rs.close();
con.close();
return list;
}
}
- Copy the following code to index.jsp and execute it.
<%--
Created by IntelliJ IDEA.
User: 86135
Date: 2021/3/10
Time: 19:58
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.liupanlong.readMysql.Hello_table" %>
<%@ page import="com.liupanlong.readMysql.readhello" %>
<%@ page import="java.util.List" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>查询hello表格</title>
</head>
<body>
<style>
body,table {text-align: center;} table {margin: auto;}
</style>
<table border="1">
<tr>
<td width="100">id</td>
<td width="100">name</td>
</tr>
<%
readhello dao=new readhello();
List<Hello_table> list = dao.readFirstHello();
for(Hello_table tl:list)
{%>
<tr>
<td width="100"><%=tl.getId() %></td>
<td width="100"><%=tl.getName() %></td>
</tr>
<%}
%>
</table>
</body>
</html>
Use Tomcat to run, open the browser and localhost:8080/web/index.jsp
finally that's it.
In mysql table like this
Fourth, the experiment summary
Encounter problems:
1. There is no Java Enterprise option in IDEA to create a java web project.
It is said that this is caused by the new version of IDEA, first create an ordinary java project, and then upgrade to a web project. (The name I created here is readMysql)
Right-click to add framework support
and it will be there, as shown in the figure and click OK.
2. Tomcat Garbled
In the conf folder, find the logging.properties file and open it. Use Ctrl + F keys to find "ConsoleHandler.encoding"
will
java.util.logging.ConsoleHandler.encoding = UTF-8
Change the UTF-8 in GBK to GBK encoding
java.util.logging.ConsoleHandler.encoding = GBK
Then restart tomcat