在Java数据库开发中,连接数据库是第一步。使用JDBC的基本代码如下:
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
try {
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
案例一:用户管理系统
用户管理系统是Java数据库开发的经典案例。首先创建数据库表:CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50), email VARCHAR(100)); 然后使用PreparedStatement插入数据:PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (name, email) VALUES (?, ?)"); pstmt.setString(1, "张三"); pstmt.setString(2, "zhangsan@email.com"); pstmt.executeUpdate();
案例二:商品库存查询
商品库存系统需要实现查询功能。SQL语句:SELECT product_name, stock FROM products WHERE category = ?; 在Java中:String sql = "SELECT product_name, stock FROM products WHERE category = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, "电子产品"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String name = rs.getString("product_name"); int stock = rs.getInt("stock"); System.out.println(name + ": " + stock); }
案例三:订单处理系统
订单系统涉及事务处理。代码示例:conn.setAutoCommit(false); try { PreparedStatement pstmt1 = conn.prepareStatement("UPDATE inventory SET quantity = quantity - ? WHERE product_id = ?"); pstmt1.setInt(1, 10); pstmt1.setInt(2, 123); pstmt1.executeUpdate(); PreparedStatement pstmt2 = conn.prepareStatement("INSERT INTO orders (product_id, quantity) VALUES (?, ?)"); pstmt2.setInt(1, 123); pstmt2.setInt(2, 10); pstmt2.executeUpdate(); conn.commit(); } catch (SQLException e) { conn.rollback(); }
案例四:使用MyBatis简化开发
MyBatis配置简单。Mapper接口:public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User getUserById(int id); } XML映射: 这样就避免了大量JDBC样板代码。
案例五:Spring Boot集成JPA
Spring Boot中@Entity public class User { @Id @GeneratedValue private Long id; private String name; } Repository:public interface UserRepository extends JpaRepository
案例六:分页查询实现
分页查询SQL:SELECT * FROM users LIMIT ? OFFSET ?; Java代码:int pageSize = 10; int pageNum = 1; int offset = (pageNum - 1) * pageSize; PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users LIMIT ? OFFSET ?"); pstmt.setInt(1, pageSize); pstmt.setInt(2, offset);
FAQ
Q: 如何处理数据库连接池?
A: 使用HikariCP或Apache DBCP2,在Spring Boot中自动配置即可。
Q: JDBC和ORM哪个好?
A: 简单项目用JDBC,复杂业务用Hibernate或MyBatis。
Q: 事务怎么回滚?
A: conn.setAutoCommit(false); try{}catch{conn.rollback();} finally{conn.commit();}
Q: 如何防止SQL注入?
A: 始终使用PreparedStatement和参数绑定。