-
使用注解,将重复的代码单独放置
-
`package com.blb.jdbc;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Hello02 {
private Connection connection;
private String sql;
@Before
public void into() throws Exception {
connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/bailiban”,“root”,“123456”);
}
@Test
public void testAdd() throws Exception {
sql = "insert into bailiban.hero VALUES (null,'哈哈','男',16)";
}
@Test
public void testUpdate() throws SQLException {
sql = "update bailiban.hero set age = 13 where name = '露娜'";
}
@Test
public void testDelete() throws SQLException {
sql ="delete from bailiban.hero where id = 3"; }
@After
public void end() throws Exception {
Statement statement = connection.createStatement(); int i = statement.executeUpdate(sql); System.out.println(i); statement.close(); connection.close();
}
}`
- 将一些冗余代码写在工具类中
- `package com.blb.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class jdbcUtils {
public static void main(String[] args) throws Exception {
jdbc("insert into bailiban.hero VALUES (null,'haihai','男',16)");
/jdbc(“select * from bailiban.hero”);/
jdbc(“delete from bailiban.hero where id = 3”);
}
public static void jdbc(String sql) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bailiban", "root", "123456");
Statement stat = conn.createStatement();
int i = stat.executeUpdate(sql);
System.out.println(i);
stat.close();
conn.close();
}
}`
注意要把 Connection connection String sql私有化



