CRUD是最常见的数据库操作,即增删改查
C 增加(Create)
R 读取查询(Retrieve)
U 更新(Update)
D 删除(Delete)
在JDBC中增加,删除,修改的操作都很类似,只是传递不同的SQL语句就行了。
查询因为要返回数据,所以和上面的不一样,将在查询章节讲解。
步骤1:增加
步骤2:删除
步骤3:修改
步骤4:练习-增 删 改
步骤5:答案-增 删 改
步骤 1 : 增加
这段代码就是Hello JDBC中的代码,用于向数据库中插入数据
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
public static void main(String[] args) {
try {
Class.forName( "com.mysql.jdbc.Driver" );
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (
Connection c = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8" ,
"root" , "admin" );
Statement s = c.createStatement();
)
{
String sql = "insert into hero values(null," + "'提莫'" + "," + 313 .0f + "," + 50 + ")" ;
s.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
步骤 2 : 删除
删除和增加很类似,只不过是执行的SQL语句不一样罢了
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
public static void main(String[] args) {
try {
Class.forName( "com.mysql.jdbc.Driver" );
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (
Connection c = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8" ,
"root" , "admin" );
Statement s = c.createStatement();
)
{
String sql = "delete from hero where id = 5" ;
s.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
步骤 3 : 修改
修改也一样,执行另一条SQL语句就可以了
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
public static void main(String[] args) {
try {
Class.forName( "com.mysql.jdbc.Driver" );
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (
Connection c = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8" ,
"root" , "admin" );
Statement s = c.createStatement();
)
{
String sql = "update hero set name = 'name 5' where id = 3" ;
s.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
更多内容,点击了解: https://how2j.cn/k/jdbc/jdbc-crud/705.html