【例】创建exgample11_1.jsp页面,并在该页面中使用纯Java数据库驱动程序连接数据库test,并查询数据表goods中的数据。
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%> //导入包
访问MySql数据库
<%
Connection con = null;
Statement st = null;
ResultSet rs = null;
//加载驱动
try{
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e){
e.printStackTrace();
}
//建立连接
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8","root","root");
st = con.creatStatement();
//发送查询SQL语句,返回结果集
rs = st.excecuteQuery("select*from goods ");
while(rs.next()){
out.print(rs.getString"("id")+" ");
out.print(rs.getString"("gname")+" ");
out.print(rs.getString"("gprice")+" ");
out.print("
");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
rs.close();
st.close();
con.close();
}
%>