目录
简介:
本学期学的javaweb,记录一些
本篇大致内容就是:部署tomcat--创建项目---连接mysql数据库
运行环境:
idea2020.1、navicat for mysql
tomcat-8.5.46、JDK1.8、mysql80(也写了mysql57的设置)
一、创建项目
左上角点击file--new--project
左侧选择java enterprise----右侧第三项我是因为创建过自动的,你那里没有也没关系--下边选中Web Application

选择好后点击next

点击finish就创建好了

二、tomcat部署
1、将tomcat解压在一个自己找得到路径
例如:我的直接就在路径中最好不要中文和空格

2、在idea中添加tomacat模板块



然后点ok
3、添加tomcat服务器

这里我的因为创建过,这里建了一个新的Tomcat 8.5.462为例


点击后出现


4、测试tomcat可用否

浏览器会自动跳出,这样即正确可用
三、连接数据库
1将navicat连接MySQL
打开navicat for mysql

一个来自我同学的报错,解决方法就是给他的mysql的root修改了下密码

双击变绿,正确,说明开启了连接

1、创建一个新的数据库
右击MySQL-------》新建数据库--------》填入数据库名(我的叫:homework)--确定

双击数据库一下,绿色亮起,创建表


最后 初始的表长这样,我的表名叫user

记得往表里添加一些数据
2、为项目添加jdbc驱动包
驱动包官方下载地址:Download MySQL Connector

这里我的mysql是8.0的所以要用一个对应的包,这是我在官方下的适配mysql8.0的驱动

如果mysql57

步骤:


点击后在你的电脑中找到你的驱动包(没解压的解压)例如我的路径长这样,选中.jar文件--点ok

第二步:还是这里,点左侧Arti

右击后选putin to ---》apply-----ok

最后这里有这个就对了

3、创建jdbc类
右击src,填写包名,我的叫database

再右击创建的包(database)填写javaclass的名,我的叫JDBC

然后编写jdbc类-mysql80

//mysql80
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
//驱动类路径
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
//
private static final String URL="jdbc:mysql://localhost:3306/homework";
private static final String USER="root";
private static final String PASSWORD="123456";
private static Connection conn=null;
private static Statement stat=null;
static {
try {
//
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn(){
try {
conn = DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
//
public static Statement getStat() {
try {
stat=getConn().createStatement();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return stat;
}
public static void main(String[] args){
System.out.println(getStat());
}
}
mysql57要这样写

//mysql57
public class JDBC {
//驱动类路径
private static final String DRIVER = "com.mysql.jdbc.Driver";
//
private static final String URL="jdbc:mysql://localhost:3306/homework";
private static final String USER="root";
private static final String PASSWORD="123456";
private static Connection conn=null;
private static Statement stat=null;
static {
try {
//
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//后续不变