Home > Java > javaTutorial > javaweb link database tutorial

javaweb link database tutorial

angryTom
Release: 2019-08-02 16:36:37
forward
8941 people have browsed it

javaweb link database tutorial

Statement: I have always thought that connecting a javaweb program to a database is a very difficult problem. As a result, I studied it today and solved it in less than two hours. So to summarize blog.

 The JavaWeb program connects to the SQLserver database in the following steps:

1: at http://www.microsoft.com/en-us /download/details.aspx?id=21599Download the compressed package of sqljdbc.jar

#2: After decompression, copy and paste sqljdbc4.jar into your project In the lib directory of WEB-INF

javaweb link database tutorial

##3: You need to know some technical knowledge about databases:

First, give an example: The following are the steps required for the driver to establish a connection:

try{
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=user";
Connection conn = DriverManager.getConnection(URL, userName, userPwd);//userName是你数据库的用户名如sa,
conn.println("连接数据库成功");
conn.close();
}catch (Exception e){
   out.println("数据库连接失败");
}
Copy after login

1>: Driver interface: java.sql.Driver is required by all JDBC drivers Implemented interface, this interface is provided to different database vendors, and they use different interface names.

  -:Class name of SQLserver's JDBC driver: "com.microsoft.sqlserver.jdbc.SQLServerDriver"

  -:Class name of Oracle's JDBC driver: "oracle.jdbc .driver.OracleDriver"

  -:MySQL JDBC driver class name: "com.mysql.jdbc.Driver"

 

2>Loading and registering the JDBC driver

  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");This statement is used to load

 3>The URL representation of JDBC connection database is usually divided into three forms Part (usually: separated):

1: Protocol: The only allowed protocol in JDBC can only be jdbc.

2: Sub-protocol: Sub-protocol is used to identify a Database driver

 3: Subname: See below for details

 -:Connect to SQLserver: "jdbc:sqlserver://localhost:1433;DatabaseName=user"

 - :Connect to Oracle: "jdbc:thin:@localhost:1521:ORCL"

  -:Connect to MySQL: "jdbc:mysql://localhost:3306/databasename"

 4> ; Execute SQL statement interface Statement object, common methods of this object:

  -:void close() Close and release resources

  -:ResultSet executeQuery(String sql): Execute a certain item Query statements and return results

   -:int execulteUpdate(String sql): You can execute insert, undate or delete statements

4: Take a look at what I wrote for the first time Program to operate the database:

## 1> First create a Student class

package com.ll;
public class Student {
    private String name;
    private String time;
    private String banji;
    public String getBanji() {
        return banji;
    }
    public void setBanji(String banji) {
        this.banji = banji;
    }
    private String sex;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }
    
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}
Copy after login

2> Write the part that connects the dao layer to the database ,

package dao;
import com.ll.Student;//本行及以下是导入SQL以及所需的包  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.Statement;  
import java.util.ArrayList;  
public class Studentdao   
{  
    public ArrayList queryAllStudents() throws Exception  
    {//实现对数据库的访问  
        Connection conn = null;  
        ArrayList students = new ArrayList();//定义与初始化ArrayList数组,相当于定义数组,但是容量比数组大  
        StringBuffer str= new StringBuffer();  
        try {  
            //获取连接  
                String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  //加载JDBC驱动   
                String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=StudentManagement";  //连接服务器和数据库sample
                //运行SQL语句  
                String userName = "sa";  //默认用户名 
                String userPwd = "zongjin123";  
                Class.forName(driverName);
                conn = DriverManager.getConnection(dbURL, userName, userPwd);
                if(conn!=null)
                {
                System.out.println("Connection Successful!");  //如果连接成功 控制台输出
                }
                else{
                
                       System.out.println("Connection fail!");  
                    return students;
                }
                
            //密码 
                String sql = "select * from student";//SQL语句,选择数据表student中的所有数据  
        Statement stat = conn.createStatement();  
        ResultSet rs = stat.executeQuery(sql);//定义ResultSet类,用于接收获取的数据  
        while (rs.next())  
                {  
                     //实例化VO  
          Student student=new Student();  
                  student.setName(rs.getString("姓名"));
                  student.setBanji(rs.getString("班级"));
                  student.setSex(rs.getString("性别"));
                  student.setTime(rs.getString("年龄"));
                  students.add(student);  
        }  
                rs.close();  
        stat.close();  
                }  
              catch (Exception e1)   
            {  
            e1.printStackTrace();  
            }  
        finally  
        {  
            try  
            {//关闭连接  
                if(conn!=null)  
                {  
                    conn.close();  
                    conn=null;  
                }  
            }  
            catch(Exception ex)  
            {  
            }  
      return students;    
    }  
  }  
}
Copy after login

 3>Create index.jsp file

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@page import = "java.util.*" %>
<%@page import = "java.sql.*" %>
<%@page import="com.ll.Student" %>  
<%@page import="dao.Studentdao" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>  
    <head>  
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
               <style type="text/css">  
#body {  
    background-color: #FFD2BD;       
      }     
  </style>  
        <title>JSP Page</title>  
 </head>  
    <body id="body">  
        <h1>学生信息如下所示:</h1><br>  
        <%  
        Studentdao studentDao=new Studentdao();  
        ArrayList students=studentDao.queryAllStudents();  
        %>      
        <table  border="1" >  
            <tr >  
                <td >年龄</td>  
                <td>姓名</td>  
                 <td>性别</td>  
                <td>班级</td>  
            </tr>  
            <%  
            for(int i=0;i<students.size();i++)  
            {  
                Student student=(Student)students.get(i);  
              
           %>  
            <tr>  
                <td><%=student.getSex() %></td>  
                <td><%=student.getName() %></td>    
                 <td><%=student.getSex() %></td>  
                <td><%=student.getBanji() %></td>    
            </tr>  
            <%  
            }  
            %>  
        </table>  
    </body>  
</html>
Copy after login

 4>The premise is that you have created a table on your SQLserver database, And there is data.

5. The result is:

The above is the detailed content of javaweb link database tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template