啊今天总结一下JDBC叭,但是好像还没有学完(?
四个功能,增删改查
环境配置的话,我用的mysql是免安装版的,用cmd启动的那种,然后mysql语句是用navicat写的,emmm如果有条件我再写一篇教程好了,这篇直接写代码了
首先新建一个java类,然后再.idea这个文件夹里放入mysql-connector-java-5.0.8-bin这个jar包。
啊这里,记得要放在一个叫lib的文件夹里面
(新建一个dictionary然后拖进去就好
记得添加完之后右键让它识别到库
然后就开始写查找功能
public class find {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//加载驱动cl
Class.forName("com.mysql.jdbc.Driver"); //就是jar包里面的东西,这里就写这个文件的当前位置
//创建连接
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/test1","root","123456");
System.out.println("创建连接成功!");
//写sql语句
String sql="select * from tb_user where id=1";
//获得statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//执行sql,得到结果
ResultSet resultSet=statement.executeQuery(); //executeQuery()方法会把数据库响应的查询结果存放在ResultSet类对象中
//处理结果集
while (resultSet.next()){
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
}
//关闭资源
resultSet.close();
statement.close();
connection.close();
}
}
总结下来就是这几个步骤
- 建立连接
- 写sql语句
- 注入(?大概是这个意思)语句
- 处理结果
- 关闭资源
接下来写删除功能
public class delete {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/test1","root","123456");
System.out.println("创建连接成功!");
Connection connection= DButil.getConnection();
String sql="delete from tb_user where id=2";
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
resultSet.close();
statement.close();
connection.close();
}
道理基本是一样的,然后这句
statement.executeUpdate();
发现变成了update了,因为这个操作涉及到了数据改动,增,改这两个操作也要把用到这个
那么下面两个功能也是只有sql语句的区别了,我把sql语句贴下面叭
增:String sql="insert into tb_user values(4,'d','d')";
改:String sql="update tb_user set password='d' where id=3";
一下是一些优化~
可以说是功能都实现了,但是仔细一想可以发现,为什么不能把每个功能类里相类似的写在一起,要用的时候统一调用呢?
说干就干!
public class DButil {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
//加载驱动cl
Class.forName("com.mysql.jdbc.Driver");
//创建连接
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/test1","root","123456");
System.out.println("创建连接成功!");
return connection;
}
//关闭资源
public static void closeAll(ResultSet resultSet, Statement statement,Connection connection) throws SQLException {
if (resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
}
}
为什么要在关闭资源的时候弄一个判断呢?
如果当时已经是关闭状态下,在运行关闭语句可能会出错,所以要进行判断
来看一个调用的例子,这次用删除的
public class delete {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//连接
Connection connection= DButil.getConnection();
String sql="delete from tb_user where id=2";
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
//关闭
DButil.closeAll(null,statement,connection);
}
}
注意:在关闭的那个方法,里面也写方法对应的值
然后差不多了
有什么错误欢迎提出来嗷