JDBC练习
练习:
account表 添加一条记录
public class JdbcDemo02 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
String sql = "insert into account values(null,'王五',3000.0)";
Connection coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/root", "root", "root");
Statement stmt = coon.createStatement();
int count = stmt.executeUpdate(sql);
if (count > 0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
}
}
account表 修改记录
public class JdbcDemo01 {
public static void main(String[] args) throws Exception {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取数据库连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/root", "root", "root");
//定义sql
String sql = "update account set balance = 1000 where id = 3";
//获取执行sql语句的对象 Statement
Statement stmt = conn.createStatement();
//执行sql,接受返回结果
int count = stmt.executeUpdate(sql);
//处理结果
System.out.println(count);
//释放资源
conn.close();
stmt.close();
}
}
account表 删除一条记录
public class JdbcDemo03 {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/root", "root", "root");
String sql = "delete from account where id = 5";
Statement sttm = conn.createStatement();
int i = sttm.executeUpdate(sql);
if (i > 0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}
}