新建一个java class取名(DBUtil)
DBUtil是如下代码,加入getConnection与closeAll方法简化之前的增删改查操作。
package com.zhongruan;
import java.sql.*;
public class DBUtil {
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/zjgm?user=root&password=123456&characterEncoding=utf-8&useSSL=true");
return connection;
}
public static void closeAll(ResultSet resultSets, Statement statement, Connection connection)throws SQLException{
if (resultSets!=null){
resultSets.close();
}
statement.close();
connection.close();
}
}
增
package com.zhongruan;
import java.sql.*;
public class tianjia {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
//2.创建连接
DBUtil dbUtil=new DBUtil();
Connection connection=dbUtil.getConnection();
//3.写sql
String sql ="insert into stu (name,age) values ('拉拉拉','24')";
//4.得到statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//5.执行sql
//ResultSet resultSets =
statement.executeUpdate();
//6.处理结果集
//7.关闭资源
dbUtil.closeAll(null,statement,connection);
}
}
删
package com.zhongruan;
import java.sql.*;
public class shanchu {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
//2.创建连接
DBUtil dbUtil=new DBUtil();
Connection connection=dbUtil.getConnection();
//3.写sql
String sql ="delete from stu where id=1";
//4.得到statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//5.执行sql
//ResultSet resultSets =
statement.executeUpdate();
//6.处理结果集
//7.关闭资源
dbUtil.closeAll(null,statement,connection);
}
}
改
package com.zhongruan;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class xiugai {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
//2.创建连接
DBUtil dbUtil=new DBUtil();
Connection connection=dbUtil.getConnection();
//3.写sql
String sql ="update stu set name='嘤嘤怪' where id=5";
//4.得到statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//5.执行sql
//ResultSet resultSets =
statement.executeUpdate();
//6.处理结果集
//7.关闭资源
dbUtil.closeAll(null,statement,connection);
}
}
查
package com.zhongruan;
import java.sql.*;
public class chaxun {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
//2.创建连接
DBUtil dbUtil=new DBUtil();
Connection connection=dbUtil.getConnection();
//3.写sql
String sql ="select * from stu where age=20";
//4.得到statement对象
PreparedStatement statement=connection.prepareStatement(sql);
//5.执行sql
ResultSet resultSets = statement.executeQuery();
//6.处理结果集
while (resultSets.next()){
int id=resultSets.getInt(1);
String name=resultSets.getString(2);
int age=resultSets.getInt(3);
System.out.println(id+name+age);
}
//7.关闭资源
dbUtil.closeAll(resultSets,statement,connection);
}
}