JSP数据库操作和调用自己写的java类

作为新手在这卡了很久,其实是个小问题

调用数据库没有直接用jsp直接调用数据,因为不知道为什么那个drive总是配置不好

而是打算用java访问数据库,再让jsp调用Java的接口

 

java代码:

java必须有个自己的包,不能用默认的包名

package test;
import java.sql.*;

public class Mysql {
    
    public Mysql(){

        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名scutcs
        String url = "jdbc:mysql://127.0.0.1:3306/ems";
        String user = "root";
        String password = "";
        try {
            // 加载驱动程序
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, user, password);
            if(!conn.isClosed())
                System.out.println("Succeeded connecting to the Database!");
            // statement用来执行SQL语句
            Statement statement = conn.createStatement();
            // 要执行的SQL语句
            String sql = "select * from pm2_5";
            
            ResultSet rs = statement.executeQuery(sql);
            System.out.println("-----------------");  
            System.out.println("-----------------");
            String name = null;
            while(rs.next()){ 
                name = rs.getString("mark");
                //name = new String(name.getBytes("ISO-8859-1"),"utf-8");
                //输出结果
                System.out.println(rs.getString("id") + "\t" + name);  
            }  
            rs.close();
            conn.close();
        } catch(ClassNotFoundException e) {
            System.out.println("Sorry,can`t find the Driver!");   
            e.printStackTrace();   
        } catch(SQLException e) {   
            e.printStackTrace();   
        } catch(Exception e) {   
            e.printStackTrace();   
        }
    }
}

jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.*" import="java.io.IOException"%>
<%@ page import="test.Mysql" %>
<%
    out.println("哈哈");
    new Mysql();
%>

控制台输出:

Succeeded connecting to the Database!
-----------------
-----------------
1    E354266E-D5CF-8384-D589-A179F92AFEE5
2    E354266E-D5CF-8384-D589-A179F92AFEE5
3    E354266E-D5CF-8384-D589-A179F92AFEE5
4    E354266E-D5CF-8384-D589-A179F92AFEE5
5    E354266E-D5CF-8384-D589-A179F92AFEE5
6    E354266E-D5CF-8384-D589-A179F92AFEE5
7    E354266E-D5CF-8384-D589-A179F92AFEE5
8    E354266E-D5CF-8384-D589-A179F92AFEE5
9    E354266E-D5CF-8384-D589-A179F92AFEE5
10    E354266E-D5CF-8384-D589-A179F92AFEE5
11    E354266E-D5CF-8384-D589-A179F92AFEE5
12    E354266E-D5CF-8384-D589-A179F92AFEE5
13    E354266E-D5CF-8384-D589-A179F92AFEE5
14    E354266E-D5CF-8384-D589-A179F92AFEE5
15    E354266E-D5CF-8384-D589-A179F92AFEE5
16    E354266E-D5CF-8384-D589-A179F92AFEE5

 

然后封装下java类就行了^_^

posted @ 2015-04-12 23:18  冰雪一舟  阅读(924)  评论(0编辑  收藏  举报