IDEA创建maven项目连接数据库
前言: 要有mysql,有要使用的表。
1.不用骨架创建maven项目
不会的请看文中是模块,可以改为新建项目,都一样
2.创建以下项目结构
3.添加依赖
demo:
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
也可以在这里找,我只列出第一个依赖的网址:mysql-connector-java
其他的也可以在该网址找。
4.代码
package com.cs.domain;
public class User {
private String sid;
private String sname;
private String password;
@Override
public String toString() {
return "User{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", password='" + password + '\'' +
'}';
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.cs.dao;
import com.cs.domain.User;
import java.util.List;
public interface IUserDao {
List<User> findAll() throws Exception;
}
数据库连接的一些参数不懂请看Java使用IDEA连接数据库的配置
package com.cs.dao.Impl;
import com.cs.dao.IUserDao;
import com.cs.domain.User;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements IUserDao {
public List<User> findAll() throws Exception {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/school?useSSL=FALSE&serverTimezone=UTC","root","root");
//获取预处理对象
PreparedStatement ps = conn.prepareCall("select * from student");
//执行sql
ResultSet rs = ps.executeQuery();
//封装user
List<User> users = new ArrayList<User>();
while(rs.next()){
User user = new User();
user.setSid(rs.getString("sid"));
user.setSname(rs.getString("sname"));
user.setPassword(rs.getString("password"));
users.add(user);
}
//释放资源
rs.close();
ps.close();
conn.close();
return users;
}
}
package com.cs.test;
import com.cs.dao.IUserDao;
import com.cs.dao.Impl.UserDaoImpl;
import com.cs.domain.User;
import org.junit.Test;
import java.util.List;
public class UserTest {
@Test
public void findAll() throws Exception {
IUserDao userdao = new UserDaoImpl();
List<User> users = userdao.findAll();
System.out.println(users);
}
}