JDBC的CRUD操作
JDBC的CRUD操作就是指利用JAVA编程实现数据库(mysql)的增删改查。
首先需要一个连接数据库的类或文件,里面放对应url,user,pwd及驱动。
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3308/db_ishop?serverTimezone=UTC&allowPublicKeyRetrieval=true&useSSL=false
user = root
pass = 123456
再通过connection对象连接数据库
public int createGoodsType(GoodsType goodsType){
//定义sql语句
String sql = "insert into t_goodstype (typename) values(?)";
//获取数据库连接对象
Connection conn = super.getConnection();
//创建preparedstatement:1性能更好2.防止SQL注入
PreparedStatement ps = null;
int result = 0;
try {
ps = conn.prepareStatement(sql);
//给占位符赋值
ps.setString(1,goodsType.getTypeName());
//因为是inster操作,则执行update
result = ps.executeUpdate(); //如果成功,返回数据条数
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//统一释放连接资源
super.closeConnection(null,ps,conn);
}
return result;
};