Java jdbc增删查改
时间: 2023-12-04 22:40:39 浏览: 86
以下是Java JDBC实现增删改查的示例代码:
1. 连接数据库
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
```
2. 实现数据库的查询
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
public User getUserById(int id) {
User user = null;
Connection conn = DBUtil.getConnection();
String sql = "select * from user where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
```
3. 实现数据库的删除
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UserDao {
public boolean deleteUserById(int id) {
Connection conn = DBUtil.getConnection();
String sql = "delete from user where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
int result = ps.executeUpdate();
if (result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
```
4. 实现数据库的增添
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UserDao {
public boolean addUser(User user) {
Connection conn = DBUtil.getConnection();
String sql = "insert into user(name, age) values(?, ?)";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setInt(2, user.getAge());
int result = ps.executeUpdate();
if (result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
```
5. 实现数据库数据的修改
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UserDao {
public boolean updateUser(User user) {
Connection conn = DBUtil.getConnection();
String sql = "update user set name=?, age=? where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setInt(2, user.getAge());
ps.setInt(3, user.getId());
int result = ps.executeUpdate();
if (result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
```
阅读全文