• Java Servlet调用数据库复习


    首先要导入jar包。

    剩下的基本就是模版式的代码了:

    public class main {
    	
    	// JDBC 驱动名及数据库 URL
    		static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    		static final String DB_URL = "jdbc:mysql://localhost:3306/test";//端口号,数据库名
        
        
    		
    		// 数据库的用户名与密码,需要根据自己的设置
    		static final String USER = "root";
    		static final String PASS = "";
    	
    	public static void main(String args[]){
    		
    		Connection conn = null;
    		Statement stmt = null;
    		try{
    			// 注册 JDBC 驱动
    			Class.forName("com.mysql.jdbc.Driver");
    		
    			// 打开链接
    			System.out.println("连接数据库...");
    			conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
    		
    			// 执行查询
    			System.out.println(" 实例化Statement对...");
    			stmt = (Statement) conn.createStatement();
    			String sql;
    			
    			sql = "INSERT INTO students VALUES("li","1234")";//向数据库中插入数据
    		    stmt.executeUpdate(sql);
    			
    			sql = "SELECT unmber, name FROM students";
    			ResultSet rs = stmt.executeQuery(sql);
    			
    		
    			// 展开结果集数据库
    			while(rs.next()){
    				// 通过字段检索
    				
    				String name = rs.getString("name");
    				String id = rs.getString("unmber");
    	
    				// 输出数据
    				System.out.print("ID: " + id);
    				System.out.print(", 名称: " + name);
    				
    				System.out.print("
    ");
    			}
    			// 完成后关闭
    			rs.close();
    			stmt.close();
    			conn.close();
    		}catch(SQLException se){
    			// 处理 JDBC 错误
    			se.printStackTrace();
    		}catch(Exception e){
    			// 处理 Class.forName 错误
    			e.printStackTrace();
    		}finally{
    			// 关闭资源
    			try{
    				if(stmt!=null) stmt.close();
    			}catch(SQLException se2){
    			}// 什么都不做
    			try{
    				if(conn!=null) conn.close();
    			}catch(SQLException se){
    				se.printStackTrace();
    			}
    		}
    		System.out.println("Goodbye!");
    	}
    		
    		
    		
    		
    	
    
    }            
    

    Servlet通过java调用数据库

    基本上与java直接调用一模一样。

    但是有一点很重要!!!!!!!!!!!

    千万不要把jar包导入到web项目下,会报ClassNotFound异常。

    把jar包删了,放到tomcat的lib下就行。

    public class Hello extends HttpServlet {
    	
    	
    	 
         
    	 private static final long serialVersionUID = 1L;
    		// JDBC 驱动名及数据库 URL
    		static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    		static final String DB_URL = "jdbc:mysql://localhost:3306/test";
    		
    		// 数据库的用户名与密码,需要根据自己的设置
    		static final String USER = "root";
    		static final String PASS = ""; 
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Hello() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		Connection conn = null;
    		Statement stmt = null;
    		// 设置响应内容类型
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		String title = "Servlet Mysql";
    		String docType = "<!DOCTYPE html>
    ";
    		out.println(docType +
    		"<html>
    " +
    		"<head><title>" + title + "</title></head>
    " +
    		"<body bgcolor="#f0f0f0">
    " +
    		"<h1 align="center">" + title + "</h1>
    ");
    		try{
    			// 注册 JDBC 驱动器
    			Class.forName("com.mysql.jdbc.Driver");
    			
    			// 打开一个连接
    			conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
    
    			// 执行 SQL 查询
    			stmt = (Statement) conn.createStatement();
    			String sql;
    			sql = "SELECT unmber, name FROM students";
    			ResultSet rs = stmt.executeQuery(sql);
    
    			// 展开结果集数据库
    			while(rs.next()){
    				// 通过字段检索
    				String name = rs.getString("name");
    				String id = rs.getString("unmber");
    	
    				// 输出数据
    				out.println("ID: " + id);
    				out.println(",名称: " + name);
    				
    				out.println("<br />");
    			}
    			out.println("</body></html>");
    
    			// 完成后关闭
    			rs.close();
    			stmt.close();
    			conn.close();
    		} catch(SQLException se) {
    			// 处理 JDBC 错误
    			se.printStackTrace();
    		} catch(Exception e) {
    			// 处理 Class.forName 错误
    			e.printStackTrace();
    		}finally{
    			// 最后是用于关闭资源的块
    			try{
    				if(stmt!=null)
    				stmt.close();
    			}catch(SQLException se2){
    			}
    			try{
    				if(conn!=null)
    				conn.close();
    			}catch(SQLException se){
    				se.printStackTrace();
    			}
    		}
    	   
    		
    		
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    	}
    
    }
    

  • 相关阅读:
    The Snail
    Oil Deposits
    杭电3784(继续xxx定律)
    poj 2395 Out of Hay
    poj 2485 Highways(简单题)
    poj 2560 || 杭电1162
    Rescue
    “中国芯”能抗衡英特尔吗?
    2013,中国计算巨头放眼国际市场
    123063天两度瘫痪:为啥不在淘宝上卖火车票?
  • 原文地址:https://www.cnblogs.com/wzben/p/5996337.html
Copyright © 2020-2023  润新知