码迷,mamicode.com
首页 > 数据库 > 详细

[javaEE] JDBC快速入门

时间:2016-07-05 23:53:49      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:

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;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import 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();
        }
    }

    /**
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

}

 

 

 

[javaEE] JDBC快速入门

标签:

原文地址:http://www.cnblogs.com/taoshihan/p/5645274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!