数据库的简单增删改查
package com.util;
import java.sql.*;
public class DButil {
public static Connection getConnection() throws ClassNotFoundException, SQLException{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wzsxy","root","123456");
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();
}
}
}
增
package com;
import com.util.DButil;
import java.sql.*;
public class add {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection= DButil.getConnection();
System.out.println("success!");
//写sql语句
String sql="insert into tb_user values('3','momo3','345')";
//获得statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//执行spl,得到结果集
statement.executeUpdate();
//处理结果集
//关闭资源
DButil.closeAll(null,statement,connection);
}
}
删
package com;
import com.util.DButil;
import java.sql.*;
public class Delete {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection= DButil.getConnection();
System.out.println("success!");
//写sql语句
String sql="delete from tb_user where id=2";
//获得statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//执行spl,得到结果集
statement.executeUpdate();
//处理结果集
//关闭资源
DButil.closeAll(null,statement,connection);
}
}
改
package com;
import com.util.DButil;
import java.sql.*;
public class change {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection= DButil.getConnection();
System.out.println("success!");
//写sql语句
String sql="update tb_user set username='momo4' where id='1' ";
//获得statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//执行spl,得到结果集
statement.executeUpdate();
//处理结果集
//关闭资源
DButil.closeAll(null,statement,connection);
}
}
查
package com;
import com.util.DButil;
import java.sql.*;
public class Find {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection connection= DButil.getConnection();
System.out.println("success!");
//写sql语句
String sql="select * from tb_user";
//获得statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//执行spl,得到结果集
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);
}
}