web项目连接数据库
时间: 2023-10-24 08:10:02 浏览: 101
要在web项目中连接数据库,需要先选择合适的数据库管理系统,如MySQL、Oracle、MongoDB等。然后在项目中使用对应的驱动程序(如jdbc)来连接数据库,并且在代码中编写相应的SQL语句来操作数据库。
下面是一个Java web项目连接MySQL数据库的示例:
1. 在pom.xml文件中添加MySQL驱动依赖
```xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
```
2. 在项目中编写连接MySQL数据库的代码
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseUtil {
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.cj.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
}
```
3. 在代码中使用Connection对象执行SQL语句,例如:
```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;
try (Connection conn = DatabaseUtil.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user WHERE id=?")) {
ps.setInt(1, id);
try (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;
}
}
```
阅读全文