jsp连接sql数据库
使用工具:myeclipse 2016、sql server2008、Microsoft JDBC Driver 6.0
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<title>查询所有用户的记录</title>
<style>
td{width:100px;border:2px solid;}
</style>
</head>
<body>
<%
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=shopping";//连接数据库的url地址
String user = "sa";//登录数据库的用户名
String password = "12345";//登录数据库的用户名的密码
Connection conn = null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//加载JDBC驱动程序
}
catch(Exception ex)
{
System.out.println("错误"+ex);
}
try{
conn = DriverManager.getConnection(url,user,password);//链接数据库
}
catch(Exception ex)
{
System.out.println("连接数据库错误"+ex);
}
Statement stmt = conn.createStatement();//创建语句对象Statement
String queryAll = "SELECT * FROM items";//查询所有的用户
ResultSet rs = stmt.executeQuery(queryAll);
while(rs.next()){
%>
<table>
<tr>
<td><%=rs.getInt("id") %></td>
<td><%=rs.getString("name") %></td>
<td><%=rs.getString("city") %></td>
<td><%=rs.getInt("price") %></td>
<td><%=rs.getInt("number") %></td>
<td><%=rs.getString("picture") %></td>
</tr>
<%} %>
</table>
</body>
</html>
注意:
驱动包必须放到项目的WebRoot/web-inf/lib下
如图: