在不使用Spring/JPA/Hibernate的情况下传递JDBC连接,可以通过以下几个步骤来实现:
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcConnection {
private static Connection connection;
public static Connection getConnection() {
if (connection == null) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name", "your_username", "your_password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
}
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 connection = JdbcConnection.getConnection();
String sql = "SELECT * FROM user WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
public class Main {
public static void main(String[] args) {
UserDao userDao = new UserDao();
User user = userDao.getUserById(1);
if (user != null) {
System.out.println("User ID: " + user.getId());
System.out.println("User Name: " + user.getName());
System.out.println("User Age: " + user.getAge());
} else {
System.out.println("User not found.");
}
}
}
这样,就可以在不使用Spring/JPA/Hibernate的情况下通过JDBC连接数据库,并执行相应的SQL语句。
领取专属 10元无门槛券
手把手带您无忧上云