以插入数据为例
@Test
public void insert() throws SQLException {
System.out.println("开始插入");
//获得连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/newdb3","root","");
//创建命令对象
Statement st = conn.createStatement();
//执行sql
String sql = "insert into emp(empno,ename) values(101,'tom')";
//这个方法返回int值,值为sql语句运行后受影响的行数
int num = st.executeUpdate(sql);
System.out.println("受影响的行数"+num);
System.out.println("over");
conn.close();
}
- @Test是注解,表示这个类是测试类。不需要main方法也可以直接执行。运行时在方法内点击右键运行。
- executeUpdate这个方法的返回值是sql语句运行后受影响的行数
- 最后关闭。删改过程一样,需要修改sql即可。
public class JdbcDemo2 {
@Test
public void delete() throws SQLException {
System.out.println("开始删除");
//获得连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/newdb3","root","");
//获得执行对象
Statement st = conn.createStatement();
//执行sql
String sql = "delete from emp where empno=100";
//这个方法返回int值,值为sql语句运行后受影响的行数
int num = st.executeUpdate(sql);
System.out.println("受影响的行数"+num);
System.out.println("over");
conn.close();
}
@Test
public void update() throws SQLException {
System.out.println("开始修改");
//获得连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/newdb3","root","");
//获得执行对象
Statement st = conn.createStatement();
//执行sql
String sql = "update emp set ename='Jreey' where empno=101";
//这个方法返回int值,值为sql语句运行后受影响的行数
int num = st.executeUpdate(sql);
System.out.println("受影响的行数"+num);
System.out.println("over");
conn.close();
}
@Test
public void select(){
System.out.println("开始查询");
}
}



