表结构
id:int类型
name: varchar类型
pass: varchar类型
获得连接对象
public Connection getMySQL(){
Connection connection = null;
//1.注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/mybatis?characterEncoding=utf8&connectionTimeZone=Asia/Shanghai";
connection = DriverManager.getConnection(url, "root", "root");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
新增数据
public boolean addUser(){
boolean success = false;
Connection conn = getMySQL();
try {
PreparedStatement preparedStatement = conn.prepareStatement("insert into user(name,pass) values(?,?)");
preparedStatement.setString(1, "黑客联盟");
preparedStatement.setString(2, "黑客联盟");
int i = preparedStatement.executeUpdate();
if(i>=1){
success = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return success;
}
查询数据
public List<User> queryUsers(){
List<User> list=new ArrayList<>();
Connection conn = getMySQL();
try {
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from user");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String pass = rs.getString("pass");
User u = new User(id,name,pass);
list.add(u);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
修改数据
public boolean updateUser(){
boolean success = false;
Connection conn = getMySQL();
try {
PreparedStatement preparedStatement = conn.prepareStatement("update user set name=?,pass=? where id=1");
preparedStatement.setString(1, "pingchas1");
preparedStatement.setString(2, "pingchaspass1");
int i = preparedStatement.executeUpdate();
if(i>=1){
success = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return success;
}
删除数据
public boolean deleteUser(){
boolean success = false;
Connection conn = getMySQL();
try {
PreparedStatement preparedStatement = conn.prepareStatement("delete from user where id=1");
int i = preparedStatement.executeUpdate();
if(i>=1){
success = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return success;
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END