安卓(java)連接sqlserver 執行存儲過程步驟

1>帶參數的新增用戶存儲過程:

CREATE PROCEDURE [dbo].[p_Insert_User]
@name nvarchar(50),
@UserPwd nvarchar(50)
AS
BEGIN
    INSERT INTO tb_User VALUES(NEWID(),@name,@UserPwd)
END

2>不帶參數的查詢用戶信息存儲過程:

CREATE PROCEDURE [dbo].[p_Select_User]
AS
BEGIN
    SELECT * FROM tb_User
END

3>帶參數有輸出參數的存儲過程:

CREATE PROCEDURE [dbo].[p_Select_UserCount]
@name nvarchar(50),
@result int output
AS
BEGIN
    SELECT @result= COUNT(0) FROM tb_User WHERE @name=UserName
END

4>做好準備工作之後新建java項目,導入sqljdbc.jar


package com.Project_DataBase01;

import java.sql.Connection;
import java.sql.DriverManager;

public class SelectQuery {

    private Connection conn;

    /*
     * 創建一個返回Connection的方法
     */
    public Connection getConnection(){
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            System.out.println("數據庫驅動加載成功");
            conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=java_conn_test","sa","123456");
            if(conn==null){
                System.out.println("數據庫連接失敗");
                System.out.println("-----------------------");
            }else {
                System.out.println("數據庫連接成功");
                System.out.println("-----------------------");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return conn;
    }

}

5>執行存儲過程:

package com.Project_DataBase01;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Types;

public class StartMain {

    private static Connection conn;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        conn=new SelectQuery().getConnection();

        GetProduseInsert();

        GetProduseSelect02();

        GetProduseSelect();

    }

    /*
     * 執行SELECT無參數存儲過程,查詢數據
     */

    public static void GetProduseSelect(){
        if(conn==null){
            System.out.println("鏈接數據庫失敗");
        }else {
            try {
                CallableStatement cs=conn.prepareCall("{call p_Select_User()}");
                ResultSet rs=cs.executeQuery();
                while (rs.next()) {
                    String name=rs.getString("UserName");
                    String pwd=rs.getString("UserPwd");
                    String UserId=rs.getString("UserId");
                    System.out.println(name+"\t"+pwd+"\t"+UserId);
                }
                System.out.println("查詢成功");
                System.out.println("-----------------------");
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println("查詢失敗");
                System.out.println("-----------------------");
            }
        }
    }

    /*
     *執行INSERT有參數存儲過程,查詢數據 
     */
    public static void GetProduseInsert(){
        if(conn==null){
            System.out.println("數據庫連接失敗");
        }else {
            try {
                CallableStatement ic=conn.prepareCall("{call p_Insert_User(?,?)}");
                ic.setString(1, "heyangyi");
                ic.setString(2, "123");
                ic.execute();
                System.out.println("添加成功");
             }
             catch (Exception ex) {
                 //TODO: handle exception
                 System.out.println("添加失敗");
             }
        }
    }

    /*
     * 執行帶輸出參數的存儲過程
     */
    public static void GetProduseSelect02(){
        if(conn==null){
            System.out.println("數據庫鏈接失敗");
        }else {
            try {
                CallableStatement sp=conn.prepareCall("{call p_Select_UserCount(?,?) }");
                sp.setString(1,"heyangyi");
                sp.registerOutParameter(2, Types.INTEGER);
                sp.execute();
                System.out.println("查詢成功:"+sp.getInt(2));
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println("查詢失敗");
            }
        }
    }
}

自己在代碼中的實際使用代碼情況

package yunup.com.shikong.jdbc;

import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

import yunup.com.shikong.jt.OnSPDataSingListener;
import yunup.com.shikong.jt.OnSPSelectListener;
import yunup.com.shikong.utils.SPUtils;
import yunup.com.shikong.utils.StringUtils;
import yunup.com.shikong.utils.ThreadUtils;

/**
 * Created by user on 2017/8/18.
 */
public class AdbSPUtils {

    private static final String TAG = "ppppp";
    private static Connection conn;
    private static String CONNECTIP;
    private static String CONNECTPORT;
    private static String CONNECTDBNAME;
    private static String CONNECTUSERNAME;
    private static String CONNECTUSERPSW;
    private static Connection connectionUpData;
    private static ResultSet selectResultSet;
    private static CallableStatement selectSp;

    /*
     * 創建一個返回Connection的方法
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        CONNECTIP = SPUtils.readSPString(StringUtils.CONNECTIP);
        CONNECTPORT = SPUtils.readSPString(StringUtils.CONNECTPORT);
        if (!TextUtils.isEmpty(CONNECTPORT)) {
            CONNECTPORT = ":" + CONNECTPORT;
        }
        CONNECTDBNAME = SPUtils.readSPString(StringUtils.CONNECTDBNAME);
        CONNECTUSERNAME = SPUtils.readSPString(StringUtils.CONNECTUSERNAME);
        CONNECTUSERPSW = SPUtils.readSPString(StringUtils.CONNECTUSERPSW);

//            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        System.out.println("數據庫驅動加載成功");
        //conn= DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=java_conn_test","sa","123456");
        conn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + CONNECTIP + CONNECTPORT + "/" + CONNECTDBNAME + "", CONNECTUSERNAME, CONNECTUSERPSW);
        if (conn == null) {
            Log.i(TAG, "getConnection: 數據庫連接失敗");
            Log.i(TAG, "-----------------------");
        } else {
            Log.i(TAG, "getConnection: 數據庫連接成功");
            Log.i(TAG, "-----------------------");
        }

        return conn;
    }



    /*
     * 執行SELECT無參數存儲過程,查詢數據
     */

    public static void GetProduseSelect(String spName, OnSPSelectListener onSPSelectListener) {
        ThreadUtils.runOnBackThread(() -> {
            try {
                conn = getConnection();
                if (conn == null) {

                    Log.i(TAG, "GetProduseSelect:執行無參數查詢存儲過程 鏈接數據庫失敗");
                } else {
//                CallableStatement cs = conn.prepareCall("{call p_Select_User()}");
                    CallableStatement cs = conn.prepareCall(spName);
                    selectResultSet = cs.executeQuery();
                    JSONArray jsonArray = AdbSqlUtils.resultSetToJsonArry(selectResultSet);
                    ThreadUtils.runOnUiThread(() -> {
                        onSPSelectListener.OnResponse(jsonArray.toString());
                    });
//                while (rs.next()) {
//                    String name = rs.getString("UserName");
//                    String pwd = rs.getString("UserPwd");
//                    String UserId = rs.getString("UserId");
//                    System.out.println(name + "\t" + pwd + "\t" + UserId);
//                }
//                System.out.println("查詢成功");
//                System.out.println("-----------------------");
                }
            } catch (Exception e) {
                ThreadUtils.runOnUiThread(() -> {
                    onSPSelectListener.onError(e);
                });

            } finally {
                //無論什麼情況都要關閉釋放內存,要按照順序關閉
                if (selectResultSet != null) {
                    try {
                        selectResultSet.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (selectSp != null) {
                    try {
                        selectSp.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }


            }
        });
    }

    /*
     *執行INSERT有參數存儲過程,查詢數據
     */
    public static void GetProduseInsert(String sqlName, String [] spParameter, OnSPDataSingListener onSPDataSingListener) {
        ThreadUtils.runOnBackThread(()->{
        if (conn == null) {
            System.out.println("數據庫連接失敗");
        } else {
            try {
//                CallableStatement ic = conn.prepareCall("{call p_Insert_User(?,?)}");
                conn=getConnection();
                conn.setAutoCommit(false);
                CallableStatement ic = conn.prepareCall(sqlName);

                if (spParameter != null) {
                    for (int i = 0; i < spParameter.length; i++) {
                        ic.setString(i + 1, spParameter[i]);
                    }
                }
//                ic.setString(1, "heyangyi");
//                ic.setString(2, "123");
//                ic.execute();
                int i = ic.executeUpdate();
                ThreadUtils.runOnUiThread(()->{
                onSPDataSingListener.OnResponse(i);
                });
                Log.i(TAG, "GetProduseInsert: 執行更新存儲過程成功");
            } catch (Exception ex) {
                ThreadUtils.runOnUiThread(()->{
                onSPDataSingListener.onError(ex);
                });
                //TODO: handle exception
                Log.i(TAG, "GetProduseInsert: 執行更新存儲過程失敗");
//                System.out.println("添加失敗");
            }
        }
        });
    }

    /***
     * 執行帶輸出參數的存儲過程
     *
     * @param spName      儲存過程名字
     * @param spParameter 存儲過程參數,這個參數要對應住,順序不能隨意更改,第一個穿進來的就是存儲過程對應的第一個參數
     */
    public static void GetProduseSelect(String spName, String[] spParameter, OnSPSelectListener onSPSelectListener) {
        ThreadUtils.runOnBackThread(() -> {
            try {
                conn = getConnection();
                if (conn == null) {
                    Log.i(TAG, "GetProduseSelect02: 數據庫鏈接失敗");
                    return;
                } else {
//                execute yq_phone_fh_no 系統管理員
                    String sqlcall = "{call yq_phone_fh_ok(?)}";
//                CallableStatement sp=conn.prepareCall("{call p_Select_UserCount(?,?) }");
                    selectSp = conn.prepareCall(spName);
                    if (spParameter != null) {
                        for (int i = 0; i < spParameter.length; i++) {
                            selectSp.setString(i + 1, spParameter[i]);
                        }
                    }
                    selectSp.execute();
                    selectResultSet = selectSp.getResultSet();
                    JSONArray jsonArray = AdbSqlUtils.resultSetToJsonArry(selectResultSet);
                    ThreadUtils.runOnUiThread(() -> {
                        onSPSelectListener.OnResponse(jsonArray.toString());
                    });

                }
            } catch (JSONException | SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                Log.i(TAG, "GetProduseSelect02: 執行帶參查詢存儲過程失敗");
                ThreadUtils.runOnUiThread(() -> {
                    onSPSelectListener.onError(e);
                });
            } finally {
                //無論什麼情況都要關閉釋放內存,要按照順序關閉
                if (selectResultSet != null) {
                    try {
                        selectResultSet.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (selectSp != null) {
                    try {
                        selectSp.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }


            }
        });
//        catch (Exception e) {
//            e.printStackTrace();
//            Log.i(TAG, "GetProduseSelect02: 執行帶參查詢存儲過程失敗,未知異常");
//        }
    }


}

由於jdbc 連接 返回的對象都是將ResultSet對象,類似java中結果集,所以使用起來不太方便,老是,容易出錯,造成代碼累贅,這裏給出一個將ResultSet轉換成我們常用的json字符串類型的方法,這樣我們就可以將請求到的數據ResultSet轉換成json字符串,再用監聽者模式回調到主線中中,再進行處理我們就熟悉多了.

 /**
     * 將ResultSet  轉換成JsonArray
     *
     * @param rs
     * @return
     * @throws SQLException
     * @throws JSONException
     */
    public static JSONArray resultSetToJsonArry(ResultSet rs) throws SQLException, JSONException {
        // json數組
        JSONArray array = new JSONArray();
        // 獲取列數
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        // 遍歷ResultSet中的每條數據
        while (rs.next()) {

            JSONObject jsonObj = new JSONObject();
            // 遍歷每一列

            for (int i = 1; i <= columnCount; i++) {

                String columnName = metaData.getColumnLabel(i);

                String value = rs.getString(columnName);

                jsonObj.put(columnName, value);

            }
            array.put(jsonObj);
        }
        return array;

    }

我在代碼中使用的是jtds-1.2.jar 這個跟jdbc類似,哪裏不一樣還沒看,先做一個記錄,這個jar包我也上傳到我的csdn了,存儲起來以便於以後再次的使用,還有jdbc.jar也一併上傳,看看你們需要哪個,需要那個沒去下載使用吧,

資源下載地址: http://download.csdn.net/download/mynameqi/10045683?locationNum=1&fps=1

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