servlet连接数据库sqlserver例子
时间: 2023-08-08 10:04:56 浏览: 97
下面是一个基本的servlet连接SQL Server数据库的例子:
```java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DatabaseServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("text/html");
// 输出文本
PrintWriter out = response.getWriter();
out.println("<html><body>");
Connection conn = null;
Statement stmt = null;
try {
// 加载 JDBC 驱动程序
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 建立数据库连接
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=yourDBName", "yourUserName", "yourPassword");
// 执行查询
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM yourTableName");
// 输出查询结果
while (rs.next()) {
out.println("ID: " + rs.getInt("id") + "<br>");
out.println("Name: " + rs.getString("name") + "<br>");
out.println("Age: " + rs.getInt("age") + "<br>");
}
rs.close();
} catch (Exception e) {
// 处理异常
out.println("Exception: " + e.getMessage());
} finally {
// 关闭数据库连接
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
out.println("</body></html>");
}
}
```
请注意,您需要替换 `yourDBName`,`yourUserName` 和 `yourPassword` 为您的SQL Server数据库的名称、用户名和密码。此外,您还需要替换 `yourTableName` 为您要从中检索数据的表名。
阅读全文