Android連線資料庫sqlserver

qq_39568555發表於2020-11-25

 

Android studio 要先引入 jtds-1.2.7.jar 

 

幫助類

package com.example.util;

import android.util.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SqlServerDBUtil {
    private static String driver = "net.sourceforge.jtds.jdbc.Driver";//sqlserver 驅動
    private static String url = "jdbc:jtds:sqlserver://118.124.8.100:3303;DatabaseName=databasename;useunicode=true;characterEncoding=UTF-8";//MYSQL資料庫連線Url
    //;useunicode=true;characterEncoding=UTF-8
    private static String user = "root";//使用者名稱
    private static String password = "root";//密碼

    private static Connection getConn(){

        Connection connection = null;
        try{
            Class.forName(driver);// 動態載入類
            // 嘗試建立到給定資料庫URL的連線
            connection = DriverManager.getConnection(url ,user, password);
            Log.e("sqlDBUtils","載入驅動成功");
        }catch (Exception e){
            Log.e("sqlDBUtils","載入驅動失敗");
            e.printStackTrace();
        }

        return connection;
    }

    public int logo(String sql){
        int num = 0;
        System.out.println(sql);
        Connection connection=getConn();
        try {
            if(connection!=null){
                Statement stmt = connection.createStatement();//
                if(stmt!=null){
                    // 執行sql查詢語句並返回結果集
                    ResultSet result =stmt.executeQuery(sql);
                    if (!result.next()) {
                        num = 0;
                    } else {
                        num = 1;
                    }
                    connection.close();
                    stmt.close();
                    result.close();
                }else{
                    return num;
                }
            }else{
                return num;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        System.out.println(num);
        return num;
    }
    public static List select(String sql){
        HashMap<String, Object> map = new HashMap<>();
        List list=new ArrayList<>();
        // 根據資料庫名稱,建立連線
        Connection connection = getConn();
        try {
            // mysql簡單的查詢語句。這裡是根據MD_CHARGER表的NAME欄位來查詢某條記錄
            sql = "select * from clienter";
            if (connection != null){// connection不為null表示與資料庫建立了連線
                Log.e("sqlDBUtils","成功");
                PreparedStatement ps = connection.prepareStatement(sql);
                if (ps != null){
                    // 設定上面的sql語句中的?的值為name
//                    ps.setString(1, name);
                    // 執行sql查詢語句並返回結果集
                    ResultSet rs = ps.executeQuery();
                    if (rs != null){
                        int count = rs.getMetaData().getColumnCount();
                        Log.e("sqlDBUtils","列總數:" + count);
                        while (rs.next()){
                            System.out.println("sched_name:"+rs.getString("sched_name"));
                            System.out.println("lock_name:"+rs.getString("lock_name"));
                            list.add(rs.getString("sched_name")+"   " + rs.getString("lock_name"));
                            // 注意:下標是從1開始的
                            for (int i = 1;i <= count;i++){
                                String field = rs.getMetaData().getColumnName(i);
                                map.put(field, field);
                            }
                        }
                        connection.close();
                        ps.close();
                        return  list;
                    }else {
                        Log.e("sqlDBUtils","讀取失敗");
                        return null;
                    }
                }else {
                    Log.e("sqlDBUtils","查詢失敗");
                    return  null;
                }
            }else {
                Log.e("sqlDBUtils","連線失敗");
                return  null;
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.e("sqlDBUtils","異常:" + e.getMessage());
            return null;
        }
    }
}

 

 

因為Android連線資料需要重新開執行緒,不能在原執行緒中連線資料庫

所以

 

在要連線的Activity中新增以下程式碼
//頂部訊息
@SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x11:
                    //跳轉頁面
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                case 0x12:
                    Toast.makeText(LoginActivity.this, "賬戶密碼錯誤,重新輸入!", Toast.LENGTH_LONG).show();
                    break;
            }

        }
    };
// 建立一個執行緒來連線資料庫並獲取資料庫中對應表的資料
  public void lianjie(){

      new Thread(new Runnable() {
        @Override
         public void run() {
           Message message = handler.obtainMessage();
           //呼叫連線資料庫幫助類
           SqlServerDBUtil sqlServerDBUtil=new SqlServerDBUtil();
           //自定義查詢語句sql,並接收返回值
           int logo = sqlServerDBUtil.logo("select * from operationer where bh="+username+" and password = "+userpwd);
            if(logo>0){
                  message.what = 0x11;//登入成功,表示有資料
               }else{
                  message.what = 0x12;
               }
                // 發訊息通知主執行緒更新UI
                handler.sendMessage(message);
               }
        }).start();

    }

 

 

相關文章