[javaEE] JDBC快速入门

前端之家收集整理的这篇文章主要介绍了[javaEE] JDBC快速入门前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

JDBCJava Data Base Connectivity java数据库连接

 

1.组成JDBC的两个包:主要是接口

java.sql javax.sql

2.相应JDBC数据库实现

 

tomcat的目录下面添加MysqL-connector-java-5.0.8-bin.jar这个数据库驱动包

 

package com.tsh.web;

import java.io.IOException;
 java.sql.Connection;
 java.sql.DriverManager;
 java.sql.ResultSet;
 java.sql.Statement;

 javax.servlet.ServletException;
 javax.servlet.http.HttpServlet;
 javax.servlet.http.HttpServletRequest;
 javax.servlet.http.HttpServletResponse;

/**
 */
public class DbServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     */
    public DbServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {

        try {
             注册数据库驱动
            DriverManager.registerDriver(new Driver());
            使用反射的方式
            Class.forName("com.MysqL.jdbc.Driver");
            获取数据库连接,导包的时候,注意要导java.sql下的,面向接口编程
            Connection conn=DriverManager.getConnection("jdbc:MysqL://localhost:3306/java","root","root"获取传输器对象
            Statement statement=conn.createStatement();
            获取结果集对象
            ResultSet resultSet=statement.executeQuery("select * from user"遍历
            while(resultSet.next()){
                String username=resultSet.getString("username");
                response.getWriter().write(username);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

     doPost(HttpServletRequest request,IOException {
    }

}

 

 

 

原文链接:/javase/996843.html

猜你在找的Java SE相关文章