Java——jdbc简单增删改查
一、MySQL
使用JDBC操作数据库之前,首先你需要有一个数据库。
用于演示的数据库的表。
二、下载数据库对应的jar包并导入
三、JDBC基本操作
1.连接获取
public class DBUtil {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/wzsxy","root","123456");
}
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();
}
}
}
2.查找
public class Find {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection=DBUtil.getConnection();
String sql="select * from tb_usr";
PreparedStatement statement=connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
}
DBUtil.closeAll(resultSet,statement,connection);
}
}
3.添加
public class Insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection= DBUtil.getConnection();
String sql="insert into tb_usr(user,password) values ('zxt','zxt')";
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
DBUtil.closeAll(null,statement,connection);
}
}
4.删除
public class Delete {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection=DBUtil.getConnection();
String sql="delete from tb_usr where id=5";
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
DBUtil.closeAll(null,statement,connection);
}
}
5.改(更新)
public class Insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection= DBUtil.getConnection();
String sql="insert into tb_usr(user,password) values ('zxt','zxt')";
PreparedStatement statement=connection.prepareStatement(sql);
statement.executeUpdate();
DBUtil.closeAll(null,statement,connection);
}
}