java增删改实现
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
sql = "insert into test1.hero values(null,'jj','男',25)";
sql = "insert into test1.hero values(null,'jj','男',25)";
Statement statement = connection.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i);
statement.close();
connection.close();
两种简化方式
抽取
public class Hello02 {
private Connection connection;
private String sql;
@Before
public void init() throws SQLException {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "123456");
}
@Test
public void testAdd() throws SQLException {
sql = "insert into test1.hero values(null,'jj','男',25)";
}
@Test
public void testUpdate() throws Exception {
sql = "update hero set age=age+1 where name='jj'";
}
@Test
public void testDelete () throws SQLException {
sql = "delete from hero where name='jj'";
}
@After
public void Destory() throws SQLException {
Statement statement = connection.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i);
statement.close();
connection.close();
}
}
封装
public class jdbcUtils {
public static void main(String[] args) throws SQLException {
update("update hero set age=age+1 where name='jj'");
}
public static void update(String sql) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "123456");
Statement statement = connection.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i);
statement.close();
connection.close();
}
}
|