使用JDBC进行CRUD与数据库交互!
所贴代码均基于此表结构:
CRUD-users表结构import org.junit.Test;
import java.sql.*;
import java.util.*;
/**
* CRUD
* 使用preparedStatement防止注入进行CRUD
*/
public class PSCrudUsers {
@Test
public void testInsert() throws ClassNotFoundException, SQLException {
UUID uuid = UUID.randomUUID();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxx", "root", "xxxxx");
String sql = "insert into users(userId,username,gender,age,password) values(?,?,?,?,?);";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1, uuid.toString().replace("-", ""));
preparedStatement.setObject(2, "Ronnie");
preparedStatement.setObject(3, "male");
preparedStatement.setObject(4, 47);
preparedStatement.setObject(5, "123456");
int rows = preparedStatement.executeUpdate();
if (rows > 0) {
System.out.println("Insert success!");
} else {
System.out.println("Fail to insert!");
}
preparedStatement.close();
connection.close();
}
@Test
public void testUpdate() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxxx", "root", "xxxxxx");
String sql = "update users set password =? where username=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1, "qwer");
preparedStatement.setObject(2, "Ronnie");
int rows = preparedStatement.executeUpdate();
if (rows > 0) {
System.out.println("Update success!");
} else {
System.out.println("Fail to update!");
}
preparedStatement.close();
connection.close();
}
@Test
public void testDelete() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxxx", "root", "xxxxxx");
String sql = "delete from users where username=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1, "张三");
int rows = preparedStatement.executeUpdate();
if (rows > 0) {
System.out.println("delete success!");
} else {
System.out.println("Fail to delete!");
}
preparedStatement.close();
connection.close();
}
@Test
public void testSelect() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
//获取链接
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/xxxxx", "root", "xxxxx");
String sql = "select * from users;";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();//装当前结果集列的信息
int columnCount = metaData.getColumnCount();//列的数量
List