05-JDBC连接MySQL数据库【删除数据】
JDBC自学教程–终篇总结:
地址:http://blog.csdn.net/baidu_37107022/article/details/72600018
1.实现修改步骤
前三个步骤:注册、获得连接,创建statement对象方法,见上一节:
02-JDBC实战–JDBC查询数据库MySQL–http://blog.csdn.net/baidu_37107022/article/details/72597975
2.使用jdbc删除数据库中的数据
这里使用的是queryDemo数据库,表格为demo1student,表中数据如下:
1)删除单个数据
代码演示
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
public class Test11 {
// 删除数据
//删除单个数据
@Test
public void deleteOne() {
Connection connection = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/queryDemo";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "123");
connection = DriverManager.getConnection(url, info);
String sql = "delete from demo1student where id between ? and ? ";
ps = connection.prepareStatement(sql);
ps.setInt(1, 13);
ps.setInt(2, 17);
int num = ps.executeUpdate();
if (num > 0) {
// 如果删除成功,则打印success
System.out.println("Sucess");
} else {
// 如果删除失败,则打印Failure
System.out.println("Failure");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 5.关闭资源
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行结果:
1.删除前
2.删除后
2)删除表格中所有数据
代码演示
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
public class Test12 {
// 删除表格中所有数据
@Test
public void deleteAll() {
Connection connection = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/queryDemo";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "123");
connection = DriverManager.getConnection(url, info);
String sql = "delete from demo1student";
ps = connection.prepareStatement(sql);
int num = ps.executeUpdate();
if (num > 0) {
// 如果删除成功,则打印success
System.out.println("Sucess");
} else {
// 如果删除失败,则打印Failure
System.out.println("Failure");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 5.关闭资源
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行结果:
1.删除前
2.删除后
还没有评论,来说两句吧...