天天看點

JSP 使用JDBC連接配接 SQL Server資料庫

使用jdbc連接配接資料庫首先需下載下傳sqljdbc4.jar (點此下載下傳)

下載下傳後放入工程WEB-INF/lib目錄下并添加進工程庫:

JSP 使用JDBC連接配接 SQL Server資料庫

對jar檔案右鍵選擇:

JSP 使用JDBC連接配接 SQL Server資料庫

或者如下操作

1.

JSP 使用JDBC連接配接 SQL Server資料庫

2.

JSP 使用JDBC連接配接 SQL Server資料庫

3.

JSP 使用JDBC連接配接 SQL Server資料庫

jsp連接配接代碼:

/**注意加try-catch塊

<%@ page import="java.sql.*" %><%--
  Created by IntelliJ IDEA.
  User: Vove
  Date: //
  Time: :
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>SQl</title>
</head>
<body>
<%
    String DB_Url="jdbc:sqlserver://localhost:1433;DataName=資料庫名";
    String user="使用者名";//登陸資料庫
    String password="密碼";
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection connection= null;
    try {
        connection = DriverManager.getConnection(DB_Url,user,password);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Statement statement= null;
    try {
        statement = connection.createStatement();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    try {
        statement.executeQuery("SELECT TOP 1000 [Username]\n" +
                "      ,[Password]\n" +
                "      ,[email]\n" +
                "      ,[register_date]\n" +
                "  FROM [Vove].[dbo].[User_im]");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    ResultSet resultSet=statement.getResultSet();
    while (resultSet.next()){
        String username=resultSet.getString("Username");
        String userpassword=resultSet.getString("password");
        Date date=resultSet.getDate("register_date");
        out.println(username+"\t"+userpassword+"\t"+date+"<br>");
    }
%>
</body>
</html>
           

最後吐槽一下教科書上的Class.forName(“com.microsoft**.jdbc.sqlserver.**SQLServerDriver”);

JSP 使用JDBC連接配接 SQL Server資料庫