1、数据库连接和操作
2、数据表设计和创建
3、数据的增删改查
4、高级功能,如事务处理、存储过程等
数据库连接和操作
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBHelper { 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 | SQLException e) { e.printStackTrace(); } return conn; } }
数据表设计和创建
CREATE TABLEuser
(id
int(11) NOT NULL AUTO_INCREMENT,username
varchar(255) NOT NULL,password
varchar(255) NOT NULL, PRIMARY KEY (id
) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据的增删改查
// 增加数据 public void addUser(String username, String password) { String sql = "INSERT INTO user (username, password) VALUES (?, ?)"; try (Connection conn = DBHelper.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, username); pstmt.setString(2, password); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // 删除数据 public void deleteUser(int id) { String sql = "DELETE FROM user WHERE id = ?"; try (Connection conn = DBHelper.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, id); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // 修改数据 public void updateUser(int id, String newUsername, String newPassword) { String sql = "UPDATE user SET username = ?, password = ? WHERE id = ?"; try (Connection conn = DBHelper.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, newUsername); pstmt.setString(2, newPassword); pstmt.setInt(3, id); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } // 查询数据 public User findUserById(int id) { User user = null; String sql = "SELECT * FROM user WHERE id = ?"; try (Connection conn = DBHelper.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, id); ResultSet resultSet = pstmt.executeQuery(); if (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setUsername(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); } } catch (SQLException e) { e.printStackTrace(); } return user; }
高级功能,如事务处理、存储过程等(略)
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/646012.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复