日期:2014-05-16 浏览次数:20381 次
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <%@ page import="java.util.*" %> <!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"> <title>JSP连接MySql</title> </head> <body> <% try { //加载驱动程序 Class.forName("com.mysql.jdbc.Driver"); //创建指定数据库的URL String url = "jdbc:mysql://localhost:3306/test"; //student是创建的数据库的名字 String userName = "root"; //root是MySQL默认的用户名 String password = "123"; //123是你设置的MySQL密码 //创建连接 Connection conn = DriverManager.getConnection(url, userName,password); //创建Statement对象 Statement stmt = conn.createStatement(); //执行查询数据库操作,并返回查询的结果集 ResultSet rs = stmt.executeQuery("select * from name"); //将结果集表指针定位到第一条记录前 rs.beforeFirst(); //打印查询结果 out.print("name表的数据如下:<br>"); out.print("---------------------<br>"); out.print("学号-----姓名-----性别<br>"); out.print("---------------------<br>"); int num; String name; String sex; while (rs.next()) { num = rs.getInt("id"); name = rs.getString("name"); sex = rs.getString("sex"); out.print(num + "-----" + name + "-----" + sex); out.print("<br>"); } stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); out.println(e.getMessage()); } %> </body> </html>