先New一个Project
把mysql的jar包导入到Tomcat的lib目录下 创建数据库
create databases cs;
use cs;
create table bmxx(
bmbh char(8),
bmmc char(4)
);
insert bmxx into valuse ("1001","业务");
insert bmxx into valuse ("1002","技术");
insert bmxx into valuse ("1003","售后");
insert bmxx into valuse ("1004","管理");
index.jsp测试数据库连接代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/cs?";
String user = "root";
String password="686483";
Connection conn = null;
try{
conn = DriverManager.getConnection(url,user,password);
System.out.println("ok!!");
Statement stmt = conn.createStatement();
String command = "select * from bmxx";
ResultSet rs = stmt.executeQuery(command);
while (rs.next()){
System.out.print(rs.getInt(1)+" ");
System.out.println(rs.getString(2));
}
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
pom.xml的依赖项
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>1.0-SNAPSHOT</version>
<name>demo1</name>
<packaging>war</packaging>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.7.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
运行结果
|