java web之數據庫的連接(使用JDBC連接sql server)

一、安裝JDBC驅動程序
二、加載驅動程序並建立連接對象
1.sql server的連接代碼:
2.關於這裏的用戶名和密碼
3.解決在用sa登錄時可能出現的問題


三、建立數據庫
四、在servlet中創建語句對象並執行操作
1.Statement對象的創建
2.查詢:調用Statement對象的executeQuery()方法,得到ResultSet對象。
3.關於ResultSet對象——獲得執行結果
①.next()定位記錄
②getXxx獲得某條記錄中的列值


4.非查詢語句:使用executeUpdate()方法
5.講講可滾動、可更新的ResultSet——Statement對象創建時的三個參數
①resultType——ResultSet是否可滾動
可能值:
移動結果集遊標的方法(對於可滾動的結果集)


②concurrency——是否可通過ResultSet更新表
可能值
更新方法


五、使用預處理語句——preparedStatement對象代替Statement
preparedStatement對象的創建
創建時的參數之一sql語句的參數-“?”和對?進行賦值
執行預處理語句-查詢、更新、其他


六、一個完整的servlet示例

一、安裝JDBC驅動程序


下載SQL Server JDBC 驅動程序 6.0點擊下載,這裏我選擇的是.exe版本,如下圖: 

點擊Next->下載完成後雙擊->彈出的窗體中點擊【Unzip】按鈕 
解壓後的目錄中有一個jre7和jre8文件夾 

將對應的.jar包複製到Tomcat安裝目錄的lib目錄中或web應用程序的WEB-INF\lib目錄中 
注意jdk是什麼版本的就複製哪個文件夾下的jar包
如果不知道自己的jdk版本: 
win+R 輸入cmd 進入命令行 輸入 java -version 

二、加載驅動程序並建立連接對象

1.sql server的連接代碼:

//加載
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");、
//連接數據庫
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=xxx", user, password);1234

其中1433是SQL Server的默認端口號,DatabaseName是要連接數據庫的名稱,user是用戶名,password是登錄密碼。 
其他數據庫的連接代碼也可以通過百度找到。

2.關於這裏的用戶名和密碼

平時使用數據庫時你可能是這麼連接的: 
 
要用到用戶名和密碼的話,可以直接使用sa,按上圖方式登錄後:安全性->登錄名->sa->屬性->更改密碼 
 
然後關閉ssms,重新開啓,選擇sql server身份驗證,嘗試用sa和新的密碼登錄 


3.解決在用sa登錄時可能出現的問題

①已成功與服務器建立連接,但是在登錄過程中發生錯誤。(provider:命名管道提供程序,error:0-管道的另一端上無任何進程。)(Microsoft SQL Server,錯誤:233) 
開始—所有程序—Microsoft SQL Server 2017 —Microsoft SQL Server 2017配置管理器 
如果在這裏沒有,則右鍵我的電腦-管理,按下圖所示將右邊的“Named Pipes”和“TCP/IP”啓用 
 
再重啓SQL Server:右鍵下圖中正在運行的sql server-選擇重新啓動 


②用戶 ‘sa’ 登錄失敗。 (Microsoft SQL Server,錯誤: 18456)  
看這裏可以解決 
感覺它講得夠詳細了,這裏就不贅述了。

三、建立數據庫

和一般建立數據庫並沒有什麼不同,這裏就不說了。 
如果完全不清楚怎麼用可以查看之前的一篇博客:數據庫入門

四、在servlet中創建語句對象並執行操作

示例代碼——以查詢爲例

String sql = "SELECT * FROM products";
Statement pstmt = dbconn.Statement();
ResultSet rst = stmt.executeQuery(sql);
if(rst.next())//拋出SQLException異常
{
    //創建javaBean實例並給它賦值,並將其存儲到作用域變量中請求轉發/重定向,例如
    Product product = new Product();
    product.setProd_id(rst.getString("prod_id"));

}else {
    response.sendRedirect("/helloweb/error.jsp");
}123456789101112

1.Statement對象的創建

語句對象需要通過connection對象創建:(如上文二中建立連接對象的代碼)

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");、
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=xxx", user, password);12

創建Statement對象的三種聲明

Statement stmt = con.createStatement();
Statement stmt = con.createStatement(int resultType,int concurrency);
Statement stmt = con.createStatement(int resultType,int concurrency,int holdability);123

對於這三個參數的解釋牽涉到ResultSet對象,先看下面的內容,在之後會有解釋。

2.查詢:調用Statement對象的executeQuery()方法,得到ResultSet對象。

執行查詢語句時Statement對象調用executeQuery(Srting sql)方法,該方法的返回值是ResultSet,用於保存查詢的結果集。 
ResultSet rst = stmt.executeQuery(sql);←這樣我們就得到了ResultSet對象rst。 
注意Result對象的記錄行從1開始,而不是0。

3.關於ResultSet對象——獲得執行結果

①.next()定位記錄

rst.next()用於定位到下一條記錄。對新產生的ResultSet對象,遊標指向第一行的前面。 
該方法的返回值是Boolean,如果已無下一條記錄則返回false。

②getXxx獲得某條記錄中的列值

//當值爲String時

rst.getString(String columnName);//參數爲列名
rst.getString(int columnIndex);//參數爲列的序號,從1開始1234

4.非查詢語句:使用executeUpdate()方法

public int executeUpdate(String sql) 返回值爲受影響行數,如果語句沒有返回值則返回0。 
INSERT、CREATE TABLE、DELETE等等語句都可以使用executeUpdate()方法 
public int[] executeBatch():用於在有一個操作中發送多條SQL語句。

5.講講可滾動、可更新的ResultSet——Statement對象創建時的三個參數

使用不帶參數的.createStatement();時,resultset對象默認不可滾動、不可更新。

①resultType——ResultSet是否可滾動

可能值:

ResultSet.TYPE_SCROLL_SENSITIVE——可滾動,且當數據庫發生改變時,變化對結果集可見 
ResultSet.TYPE_SCROLL_INSENSITIVE——可滾動,但數據庫發生改變時,變化對結果集不可見 
ResultSet.TYPE_FORWARDONLY——不可滾動

移動結果集遊標的方法(對於可滾動的結果集)


  方法
  說明

  public boolean previous() throws SQLException
  遊標向前移動一行,存在合法的行返回true,不存在返回false


  public boolean first() throws SQLException
  移動遊標使其指向第一行


  public boolean last() throws SQLException
  移動遊標使其指向最後一行


  public boolean absolute(int rows) throws SQLException
  移動遊標使其指向指定行


  public boolean relative(int rows) throws SQLException
  移動遊標,參數爲相對現在在的行基準,正向前移動,負向後


  public boolean isFirst() throws SQLException
  返回遊標是否指向第一行


  public boolean isLast() throws SQLException
  返回遊標是否指向最後一行


  public int getRow()
  返回遊標所在當前行行號


②concurrency——是否可通過ResultSet更新表

可能值

ResultSet.CONCUR_READ_ONLY——只讀 
ResultSet.CONCUR_UPDATABLE——可通過ResultSet更新表

更新方法

更新: 
updateXxx,以int類型爲例:

//用指定整數x更新當前指定列
public void updateInt(int columnIndex,int x)
public void updateInt(String columnName,int x)123

updateXxx指定了更新進去的數據類型。 
public void updateRow() throws SQLException//調用updateXxx,再調用updateRow()實現修改,在調用updateRow()前可使用cancelRowUpdate()取消更新。

插入: 
①public void moveToInsertRow() throws SQLException //將遊標移到插入行,再用updateXxx修改值,再調用insertRow插入 
②public void insertRow() throws SQLException //插入一行數據 
③public void moveToCurrentRow() throws SQLException //返回當前行,也可以在insertRow() 前調用取消插入

刪除: 
public void deletetRow() throws SQLException

五、使用預處理語句——preparedStatement對象代替Statement

因爲它比Statement的效率要高。

示例代碼——依舊以查詢爲例,注意和四中Statement寫法的比較

String sql = "SELECT * FROM products WHERE prod_id=?";
PreparedStatement pstmt = dbconn.prepareStatement(sql);
pstmt.setString(1, productid);
ResultSet rst = pstmt.executeQuery();
if(rst.next())//拋出SQLException異常
{
    //創建javaBean實例並給它賦值,並將其存儲到作用域變量中請求轉發/重定向,例如
    Product product = new Product();
    product.setProd_id(rst.getString("prod_id"));

}else {
    response.sendRedirect("/helloweb/error.jsp");
}12345678910111213

preparedStatement對象的創建

它比Statement對象創建時多了一個參數——sql語句

PreparedStatement pstmt = con.prepareStatement(String sql);
PreparedStatement pstmt = con.prepareStatemen(String sql,int resultType,int concurrency);
PreparedStatement pstmt = con.prepareStatemen(String sql,int resultType,int concurrency,int holdability);123

創建時的參數之一sql語句的參數-“?”和對?進行賦值

在sql語句中用?指定參數。(或者說是佔位符) 
從字符串左側開始第一個佔位符的序號爲1,以此類推 
    pstmt.setXxx(int index, Xxx value);用於給佔位符賦值

執行預處理語句-查詢、更新、其他

注意必須要調用這些方法的無參數版,而且在執行sql語句前必須用setXxx設置好所有參數

//查詢語句
ResultSet result = pstmt.executeQuery();

//更新語句
int n = pstmt.executeUpdate();

//其他語句
Boolean b = pstmt.execute();12345678

六、一個完整的servlet示例

package com.homework7.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.homework7.bean.Product;

/**
 * Servlet implementation class QueryProductServlet
 */
@WebServlet("/queryproduct.do")
public class QueryProductServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    Connection dbconn = null;

    public void init() {

        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String dburl = "jdbc:sqlserver://localhost:1433;DatabaseName=webHomework";
        String username = "sa";
        String password = "123456";
        try {
            Class.forName(driver);
            System.out.println("數據庫驅動加載成功");  
            dbconn = DriverManager.getConnection(dburl, username, password);
            System.out.println("數據庫連接成功");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(SQLException e2) {}

    }
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryProductServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String productid = request.getParameter("productid");
        try {
            String sql = "SELECT * FROM products WHERE prod_id=?";
            PreparedStatement pstmt = dbconn.prepareStatement(sql);
            pstmt.setString(1, productid);
            ResultSet rst = pstmt.executeQuery();
            if(rst.next())
            {
                Product product = new Product();
                product.setProd_id(rst.getString("prod_id"));
                product.setPname(rst.getString("pname"));
                product.setPrice(rst.getDouble("price"));
                product.setStock(rst.getInt("stock"));
                request.getSession().setAttribute("product", product);
                response.sendRedirect("/helloweb/displayProduct.jsp");
            }else {
                response.sendRedirect("/helloweb/error.jsp");
            }
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request,response);
    }

    public void destroy() {
        try {
            dbconn.close();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

原文鏈接:https://blog.csdn.net/yogima/article/details/80614575

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章