JDBC_連接數據庫
一、配置
(一) 通過SQL Server配置管理器配置相關部分;
右鍵點擊,啟動tcp/ip協議
右鍵點擊屬性查看自己的TCP端口號,記住,后面會用到
右鍵點擊SQL Server配置管理器重啟sql server(mssqlserver)服務,使得tcp/ip協議生效。
右鍵點擊服務器,選擇屬性
記住自己更改的密碼,后面會用到。
點擊狀態
(二) 下載SQL ServerJDCB庫
https://www.microsoft.com/zh-CN/download/details.aspx?id=11774
下載第三個,解壓其中對應的類庫如:mssql-jdbc-6.4.0.jre9
<需要注意自己的JDK是哪個版本的,1.80以上的對應sqljdbc42.jar類庫>
然后進入eclipse界面,找到的當前工程文件,點擊右鍵,選中properties->Libraries->addexternal jars->找到我們剛剛下載到的sqljdbc42.jar類庫,添加即可。
百度網盤
提取碼:sv6s
(三) 新建工程,驗證是否成功連接數據庫。
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.crypto.provider.RC2Parameters;
//登陸處理
public class LoginCL extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res){
Connection ct=null;
Statement sm = null;
ResultSet rs = null;
try{
//接收用戶名和密碼
String u=req.getParameter("username");
String p=req.getParameter("passwd");
//加載驅動,不同版本sqljdbc42.jar解壓后文件夾順序不同
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//得到鏈接
ct=DriverManager.getConnection(
"jdbc:sqlserver://127.0.0.1:1433;databaseName = madb","sa","123"); //因為連接的是sql2008,不用加microsoft!!!!
sm = ct.createStatement();
rs = sm.executeQuery("select top 1 * from users where username='"+u+"' and passwd='"+p+"'");
//驗證
if(rs.next()){
res.sendRedirect("wel");
}
else{
System.out.println("登陸失敗");
}
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(sm!=null){
try {
sm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ct!=null){
try {
ct.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res){
doGet(req,res);
}
}