package cn.tedu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class DButil {
/**
*
* @Title: getConn
* @Description: TODO(获取数据库连接对象)
* @param: name 数据库名称
* @param: user 数据库用户名
* @param: password 数据库密码
* @param: @throws Exception
* @return: Connection 数据库连接对象
* @throws
*/
public static Connection getConn(String name, String user, String password) throws Exception {
// 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取连接对象
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + name + "?user="
+ user + "&password=" + password + "&characterEncoding=UTF-8&serverTimezone=Hongkong"
+ "&useSSL=false&autoReconnect=true&failOverReadOnly=false");
return con;
}
public static void DBclose(Connection con, Statement stat, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
rs = null;
}
if (stat != null) {
try {
stat.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
stat = null;
}
if (con != null) {
try {
con.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
con = null;
}
}
@Test
/**
*
* @Title: main
* @Description: TODO(测试数据库数据添加)
* @param: @param args
* @return: void
* @throws
*/
public void insert() {
Connection con = null;
Statement st = null;
try {
con = getConn("db3", "root", "root");
st = con.createStatement();
// 执行语句
st.execute("INSERT INTO t_dept VALUES (null, '妖怪部','xx')");
System.out.println("执行完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBclose(con, st, null);
}
}
@Test
/**
*
* @Title: main
* @Description: TODO(测试数据库数据删除)
* @param: @param args
* @return: void
* @throws
*/
public void delete() {
Connection con = null;
Statement st = null;
try {
con = getConn("db3", "root", "root");
st = con.createStatement();
// 执行语句
st.execute("delete from t_dept where loc='xx';");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBclose(con, st, null);
}
}
@Test
/**
*
* @Title: main
* @Description: TODO(测试数据库数据修改)
* @param: @param args
* @return: void
* @throws
*/
public void update() {
Connection con = null;
Statement st = null;
try {
con = getConn("db3", "root", "root");
st = con.createStatement();
// 执行语句
st.execute("update t_dept set loc='达内' where id=6;");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBclose(con, st, null);
}
}
@Test
/**
*
* @Title: main
* @Description: TODO(测试数据库数据查找)
* @param: @param args
* @return: void
* @throws
*/
public void findAll() {
Connection con = null;
Statement st = null;
try {
con = getConn("db3", "root", "root");
st = con.createStatement();
// 执行语句
ResultSet re = st.executeQuery("select * from t_dept");
while (re.next()) {
System.out.print(re.getString(1));
System.out.print(re.getString(2));
System.out.println(re.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBclose(con, st, null);
}
}
}