JSP 使用JDBC連線 SQL Server資料庫
阿新 • • 發佈:2019-01-09
使用jdbc連線資料庫首先需下載sqljdbc4.jar (點此下載)
下載後放入工程WEB-INF/lib目錄下並新增進工程庫:
對jar檔案右鍵選擇:
或者如下操作
1.
2.
3.
jsp連線程式碼:
/**注意加try-catch塊
<%@ page import="java.sql.*" %><%--
Created by IntelliJ IDEA.
User: Vove
Date: 2017/3/17
Time: 16:25
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”);