简单玩一下:
1.pom.xml文件配置
<!--postgresql数据库依赖包-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
</dependency>
<!--jdbc依赖包-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<scope>provided</scope>
</dependency>
2.工具类
import java.sql.*;
/**
* 类名称:
*
* @author 李庆伟
* @date 2023年10月23日 10:48
*/
public class JdbcUtil {
private static final String DRIVER_NAME="org.postgresql.Driver";
//连接数据的URL路径
private static final String URL="jdbc:postgresql://localhost:5432/haha";
//数据库登录账号
private static final String USERNAME="postgres";
//数据库登录密码
private static final String PASSWORD="RBt47*XHy43GbH34";
static{
try {
Class.forName(DRIVER_NAME);
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
//创建连接
public static Connection getConnection(){
try {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//查找
public static ResultSet find(String sql) {
Connection conn = JdbcUtil.getConnection();
try {
conn.setAutoCommit(false);
Statement stat = conn.createStatement();
ResultSet result = stat.executeQuery(sql);
return result;
} catch (SQLException e) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
} finally {
}
return null;
}
//插入
public static void insert(String sql) {
Connection conn = JdbcUtil.getConnection();
Statement stat = null;
try {
stat = conn.createStatement();
stat.executeUpdate(sql);
} catch (SQLException e) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
} finally {
try {
stat.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3.测试类
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 类名称:
*
* @author 李庆伟
* @date 2023年10月23日 10:07
*/
public class DataTest {
@Test
public void firstTest() throws SQLException {
String findSql = "SELECT test_id, test_name FROM test_one;";
ResultSet rs = JdbcUtil.find(findSql);
while (rs.next()) {
String id = rs.getString("test_id");
String name = rs.getString("test_name");
System.out.println(id+"\t"+name);
}
}
@Test
public void insertTest() throws SQLException {
//String findSql = "SELECT test_id, test_name FROM test_one;";
String sql = "INSERT INTO test_one (test_id,test_name) "
+ "VALUES " + "('" + "5" + "', '" + "5" + "')";
JdbcUtil.insert(sql);
}
}
记录一点点。。。。。。。。。。。。