使用JDBC 访问数据库

来源:互联网 发布:算法推荐类app 编辑:程序博客网 时间:2024/05/16 00:58

Jdbc概述

Jdbc(Java Database Connectivity)是应用程序链接各种不同数据库的标准API,开发人员可以通过该API链接到各种不同类型的数据库管理系统,并对数据库中的数据进行操作。但是因为每种数据库的实现不相同,所以链接每种特定类型数据库时,需要使用特定的Jdbc驱动程序。Jdbc包含了两组接口:一组面向Java应用程序开发人员;一组面向驱动程序编写人员。通过使用该API,我们可以建立与数据库管理系统的链接,向服务器提交要执行的SQL语句,处理返回的结果集等。

Jdbc的分类:

类型一驱动程序:JDBC-ODBC桥,通过ODBC数据源与数据库进行连接。类型二驱动程序:通过网络库进行连接的纯Java驱动程序。类型三驱动程序:通过中间件服务器建立与数据库的链接。类型四驱动程序:直接与数据库连接的纯Java驱动程序。

链接数据库的基本过程

1.建立数据源  建立数据库,设计表格,添加数据等操作。2.引入java.sql包  在链接数据库的过程中需要用到一些接口与类,像是Driver,DriverManager,Connection,Statement,ResultSet等。这些接口和类位于java.sql包中。3.加载驱动程序  驱动程序的作用就是将用户对数据库的操作转换为数据库可以理解的形式,然后把数据库的执行结果返回给用户。如果驱动程序的名字为MyDriver,那么可以使用Class.forName("MyDriver");进行加载。4.创建于数据库的链接。  链接数据库需要的信息一般包括有:数据库的位置,数据库的信息(像是数据库的名字),用户信息(用户名,密码)。5.创建语句对象  语句对象是Statement对象,语句对象的创建是通过链接对象创建的,所以在创建语句对象之前应该确保连接对象已经创建,创建语句对象的代码如下:Statement statement=con.createStatement();6.编写SQL语句  比如: String sql="select * from tableName";7.执行SQL语句  使用语句对象执行SQL语句,执行SQL语句的方法有很多,比如:executeQuery(String sql),这个主要用于有返回结果集的操作。executeUpdate(String sql),这个主要执行没有结果返回的操作。8.处理结果集  可能你需要的结果只是结果集中的某一部分,这时就需要对返回的结果集进行处理。9.关闭相关对象  关闭连接,关闭语句,关闭结果集等。

实例演示

要求:使用Jdbsc访问数据库,使用login.jsp设计登陆页面,使用loginservlet.java验证用户输入信息,失败时使用failure.jsp处理,成功后使用failure.jsp处理。过程:1.创建数据源  W10下,我使用WAMP中的Mysql作为我的数据库,使用Navicat For MySQL进行数据库操作。首先创建数据库,建立表格,输入需要验证的用户信息。  ![表格建立完成](http://img.blog.csdn.net/20161107104603184)2.项目引入Jdbc驱动  驱动可以去相应的数据库官网上下载,注意版本号。  ![数据库驱动引入完成](http://img.blog.csdn.net/20161107104635778)3.检验数据库链接成功与否  先看看login.jsp。  代码:
<%@page language="java" import="java.util.*" pageEncoding="utf-8"%><%    String path = request.getContextPath();    String basePath = request.getScheme() + "://"            + request.getServerName() + ":" + request.getServerPort()            + path + "/";    //消除服务器端缓存操作    response.setHeader("Cache-Control", "no-store");    response.setHeader("Pragma", "no-cache");    response.setDateHeader("EXPIRES", 0);%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>Login</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><style type="text/css">.login_mainbody {    text-align: center;    margin-top: 120px;}</style></head><body>    <h2 style="color:lightgreen">用户登录</h2><hr/>    <form action="servlet/LoginServlet" method="post">        <div class="login_mainbody">            用户名<input type="text" name="username" /><br> <br>               密码<input type="password" name="password" /><br> <br>&nbsp;                <input  type="submit" value="提交" />               <input type="reset" value="重置" />        </div>    </form></body></html>

运行结果:
login.jsp的运行结果

failure.jsp代码(只是输出一句话表示失败):

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'failure.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>        登陆失败!  </body></html>

success.jsp代码(同样只输出一句话):

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'success.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>            登陆成功!  </body></html>

处理用户输入信息的loginservlet.java:

package wanghan;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@SuppressWarnings("serial")public class LoginServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");//设定文档类型        response.setCharacterEncoding("UTF-8");//设定编码格式        String username = request.getParameter("username");//获取信息        String password = request.getParameter("password");        int checknum = check("select * from users where name='" + username                + "' and password='" + password + "'");//获取数据库中匹配的记录条数        if (checknum > 0) {            response.sendRedirect("../jsp/success.jsp");//判断有的话就跳转        } else {            response.sendRedirect("../jsp/failure.jsp");        }    }    public int check(String sql) {//check函数的实现        int num = 0;        Connection connection = null;//创建链接对象        java.sql.Statement statement = null;//创建语句对象        ResultSet query = null;//创建结果集对象        try {            Class.forName("com.mysql.jdbc.Driver");//加载Mysql驱动            String driver = "jdbc:mysql://localhost:3306/test";            String user = "root";            String pass = "";            connection = DriverManager.getConnection(driver, user, pass);//构造链接            statement = connection.createStatement();//构造语句对象            query = statement.executeQuery(sql);//查询            while (query.next()) {                num++;//统计记录条数            }        } catch (Exception e) {            e.printStackTrace();//异常处理        }        if (query != null) {            try {                query.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if (statement != null) {            try {                statement.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if (connection != null) {            try {                connection.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        return num;    }}

配置的web.xml文件:

6.  <?xml version="1.0" encoding="UTF-8"?>7.  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">8.    <display-name>wanghan</display-name>9.    <servlet>10.     <servlet-name>loginServlet</servlet-name>11.     <servlet-class>wanghan.LoginServlet</servlet-class>12.   </servlet>13. 14.   <servlet-mapping>15.     <servlet-name>loginServlet</servlet-name>16.     <url-pattern>/servlet/LoginServlet</url-pattern>17.   </servlet-mapping>18. </web-app>

文件编写完成以后,可以开始运行啦

我使用的IDE是MyEclipse,加载以后使用TomCat运行,就可以看到如下结果:输入信息在数据库中存在时:![输入登录信息](http://img.blog.csdn.net/20161107110146687)![成功以后](http://img.blog.csdn.net/20161107110207065)输入信息在数据库中不存在时:![登陆失败](http://img.blog.csdn.net/20161107110246564)

总结
大家在学习的过程中,可能还会遇到各种各样的问题,这些问题可能出现在每一个方面,学习就是这样的一个过程,希望大家可以学习到更多的东西。

0 0
原创粉丝点击