原生servlet——如何连接数据库

第一步:建立好对应的项目结构:

在这里插入图片描述

BaseDao :里面 拿来 封装 连接数据的操作 StudentDaoImple 到时候 直接继承 少写很多代码
JdbcUtils: 用来获取数据库的链接
jdbc.peoperties: 用来写数据的设置

第二步:导入对应的jar包:

在这里插入图片描述

第三步 获取数据库链接:

因为这个操作经常要用到 所以写到一个工具类里面:
JdbcUtils:
没啥好说的照抄就行

public class JdbcUtils {
   


    //获取数据库的链接
    private static DruidDataSource source;
    static {
   
        try {
   
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties ps=new Properties();
            ps.load(is);
            source = (DruidDataSource) DruidDataSourceFactory.createDataSource(ps);
        } catch (Exception e) {
   
            e.printStackTrace();
        }
    }
   // :获取数据库链接
     


    public static Connection getconnection()  {
   

        Connection connection = null;
        try {
   
            connection = source.getConnection();
        } catch (SQLException e) {
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用以下步骤将servlet链接到数据库: 1. 导入相关的数据库驱动程序。 2. 在servlet中创建一个连接对象,使用驱动程序连接数据库。 3. 执行SQL查询或更新等操作。 以下是一个示例代码来链接MySQL数据库: ``` import java.sql.*; public class MyServlet extends HttpServlet { private Connection conn; public void init() { // Load MySQL JDBC driver try { Class.forName("com.mysql.jdbc.Driver"); // Create a connection to the database conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password"); } catch (Exception e) { e.printStackTrace(); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // Create a statement to execute a query Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM Customers"); // Process the result set while (rs.next()) { int id = rs.getInt("CustomerID"); String name = rs.getString("CustomerName"); String contact = rs.getString("ContactName"); String country = rs.getString("Country"); } // Close the statement and result set rs.close(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } public void destroy() { try { // Close the connection conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们使用`Class.forName`方法来加载MySQL JDBC驱动程序。然后使用`DriverManager.getConnection`方法创建一个连接对象并连接数据库。在`doGet`方法中,我们创建一个`Statement`对象来执行SQL查询,并处理结果集。在`destroy`方法中,我们关闭连接

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值