一、新建web工程
1、File->new ->project…
2、选择Maven,勾选Create from archetype,选择maven-archetype-webapp
3、next,命名工程名->next 选择maven目录和本地仓,点击Finish
4、点击Run-> Edit Configeration,点击“+”符,添加新配置,选择本地Tomcat
5、选择Deployment下的“+”符,添加xx.war exploded,修改下方的Application context 为自定义 /Demo
6、启动下方服务窗口里的Tomcat,浏览器访问http://localhost:8080/Demo/
启动成功效果如下:
二、访问数据库测试
1、src文件夹为如下状态,需要把文件夹定义为源文件夹:
定义为源文件夹后如下:
2、创建连接数据库类及创建测试类
2、访问本地数据库测试,项目文件目录如下
3、添加jar文件
4、创建配置文件
DBConfig.properties,我使用的mysql-connector-java-8.0.26.jar
对应的driver=com.mysql.cj.jdbc.Driver
内容如下:
driver=com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/db2
user=root
psd=a1234
5、新建MysqlConnection类:
package testMysql;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MysqlConnection {
public Connection getConnection(){
String driver = null;
String url = null;
String user = null;
String psd = null;
Connection conn = null;
Properties pro = new Properties();
try { pro.load(this.getClass().getClassLoader().getResourceAsStream("testMysql/DBConfig.properties"));
driver = pro.getProperty("driver");
url = pro.getProperty("url");
user = pro.getProperty("user");
psd = pro.getProperty("psd");
System.out.println("Properties:"+pro);//输出测试读取配置文件
}catch (IOException e){
e.printStackTrace();
}
try{
Class.forName(driver);//加载驱动
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try{
conn = DriverManager.getConnection(url,user,psd);
conn.setAutoCommit(false);
return conn;
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
}
6、创建测试类
鼠标选中MysqlConnection类文件名,按alt+enter,
测试类代码如下:
package test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import testMysql.MysqlConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static org.junit.Assert.*;
public class MysqlConnectionTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void getConnection() {
MysqlConnection open = new MysqlConnection();
Connection conn = open.getConnection();
System.out.println(conn);
try{
Statement state = conn.createStatement();
String sql = "select *from tab1;";
ResultSet result = state.executeQuery(sql);
String name;
while(result.next()){
name = result.getString("type");
System.out.println("type:"+name);
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
7、测试显示
三、测试连接数据库其他方式
1、新建Mysql数据库连接
选中IDEA编辑器右上侧的Database,单击“+”符号
2、添加数据库配置信息
3、添加数据库驱动
4、测试连接效果
5、回到编辑器主界面,展开刚建立的连接选项,选中需要的数据库,查看库中的表
6、点击refresh刷新数据库db2,参数设置正确的话,可刷新出该数据库下的表名,双击表名称,自动启动连接,并可看到表中的内容