其他分享
首页 > 其他分享> > 2019.09.1 改版--增删改查

2019.09.1 改版--增删改查

作者:互联网

:在包com.zhongruan下面新建一个类DButil,把“增删改查”中共用的代码打到DButil中。
如图
在这里插入图片描述
(增删改没有返回值及resultset为 NULL,所以用if来判断 )

package com.zhongruan;

import java.sql.*;

public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
DButil dButil=new DButil();
Connection connection = dButil.getConnection();
//3.写SQL
String sql=“select * from stu”;
//4.得到statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//5.执行SQL
ResultSet resultSet = statement.executeQuery();
//6.处理结果集
while (resultSet.next()){
int id=resultSet.getInt(1);
String name=resultSet.getString(2);
int age=resultSet.getInt(3);
System.out.println(id +name +age);
}
//7.关闭资源
dButil.closeAll(resultSet,statement,connection);

}

}

新建一个对象dButil------DButil dButil=new DButil()
之后就是用dButil调用。


package com.zhongruan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test2 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
DButil dButil=new DButil();
Connection connection = dButil.getConnection();
String sql=“delete from stu where id=3”;
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
dButil.closeAll(null,statement,connection);
}
}


package com.zhongruan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test4 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
DButil dButil=new DButil();
Connection connection = dButil.getConnection();
String sql=“update stu set age=21 where id=4”;
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
dButil.closeAll(null,statement,connection);
}
}


package com.zhongruan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test3 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
DButil dButil=new DButil();
Connection connection = dButil.getConnection();
String sql=“insert into stu(name,age) values (‘hhha’,12)”;
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
dButil.closeAll(null,statement,connection);
}
}

标签:2019.09,java,DButil,改查,connection,statement,sql,增删,dButil
来源: https://blog.csdn.net/A_Boxed_Man/article/details/100698315