낯선 사람 복호화(6) 데이터베이스 조작 도구와 파일 조작 클래스

힌트: 공사가 좀 커서 개인적으로는 잘 모르겠거나 논리성이 부족할 수도 있습니다. 문제가 있으면 제때에 @ 해주세요.원래 프로젝트:https://github.com/LineChen/
각 조작을 구체적으로 소개하기 전에 먼저 데이터베이스 조작 클래스와 파일 조작 클래스를 소개한다.데이터베이스:MySQL, MVC 모드 SqlHelper:
package com.database;
import java.sql.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
public class SqlHelper { String dbuserId = “root”; String dbuserPassWd = “root”; String driverName = “com.mysql.jdbc.Driver”; String url = “jdbc:mysql://localhost:3306/hello_stranger_db”; PreparedStatement ps = null; Connection ct = null; ResultSet rs = null;
//      
public boolean ConnectDb() {
    boolean isConected = true;
    try {
        Class.forName(driverName);
        ct = DriverManager.getConnection(url, dbuserId, dbuserPassWd);
    } catch (Exception e) {
        isConected = false;
        e.printStackTrace();
    }
    return isConected;

}

/**           */
public boolean create(String sql) {
    boolean isOk = true;
    try {
        ConnectDb();
        ps = ct.prepareStatement(sql);
        isOk = !ps.execute();//      ,  false     ,    
    } catch (Exception e) {
        isOk = false;
        e.printStackTrace();
    } finally {
        this.close();
    }
    return isOk;
}


/**    */
public ResultSet query(String sql, String[] paras) {
    try {
        ConnectDb();
        ps = ct.prepareStatement(sql);
        //      
        for (int i = 0; i < paras.length; i++) {
            ps.setString(i + 1, paras[i]);
        }
        rs = ps.executeQuery();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return rs;
}

/**     */
public boolean updExecute(String sql, String[] paras) {
    boolean b = true;
    try {
        ConnectDb();
        ps = ct.prepareStatement(sql);
        //  ps ?  
        for (int i = 0; i < paras.length; i++) {
            ps.setString(i + 1, paras[i]);
        }
        ps.executeUpdate();//             
        // if (ps.executeUpdate() != 1) {
        // b = false;
        // }
    } catch (Exception e) {
        b = false;
        e.printStackTrace();
    } finally {
        this.close();
    }
    return b;
}

//       
public void close() {
    try {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (ct != null)
            ct.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
구체적인 업무 논리, 모델층은 필요에 따라 상응하는 방법을 추가한다. 다음은 등록, 로그인, 비밀번호 찾기, 친구 추가, 오프라인 메시지 저장 또는 얻기 등을 포함한다.
package com.database;
import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;
import com.alibaba.fastjson.JSONObject; import com.imomo_msg.MsgDb; import com.imomo_msg.MsgKeys; import com.server_utils.FileTools;
public class SqlModel {/* 신규 사용자, 정보 수정 등 작업/public boolean updateDb(String sql, String [] paras) {//SqlHelper 만들기(프로그램의 합병성을 고려하지 않으면 정적으로 만들 수 있겠지) SqlHelper sqlHelper = new SqlHelper(), return sqlHelper. updExecute(sql,paras);
/**      */
public boolean checkUser(String userEmail, String userPasswd) {
    SqlHelper sp = null;
    boolean isLegal = false;
    try {
        //   SQL        
        String sql = "select userPasswd from imomo_clients where userEmail = ?";
        String paras[] = { userEmail };
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        if (rs.next()) {
            if (rs.getString(1).equals(userPasswd)) {
                isLegal = true;
            }
        }
    } catch (Exception e) {
        isLegal = false;
        e.printStackTrace();
    } finally {
        sp.close();
    }
    return isLegal;
}

/**
 *   Id     
 * 
 * @param userId
 * @return   null        
 */
public String getUserName(String userEmail, boolean isEmail) {
    SqlHelper sp = null;
    String userName = "null";
    try {
        String sql = null;
        if(isEmail) {
              sql = "select userName from imomo_clients where userEmail = ?";
        } else {
              sql = "select userName from imomo_clients where userId = ?";
        }
        String paras[] = {userEmail};
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        if (rs.next()) {
            userName = rs.getString(1);
        }
    } catch (Exception e) {
        userName = "null";
        e.printStackTrace();
    } finally {
        sp.close();
    }
    return userName;
}

/**
 * 
 * @param userEmail
 *                      Id
 * @param isEmail
 *                   Id   true -    false -   Id
 * @return
 */
public JSONObject getUserInfo(String userEmail, boolean isEmail) {
    JSONObject userInfo = new JSONObject();
    SqlHelper sp = null;
    String sql = null;
    try {
        if (isEmail) {
            sql = "select userId, userName, userHeadPath, userSex, userBirthday, personSignature, vitalityValue from imomo_clients where userEmail = ?";
        } else {
            sql = "select userId, userName, userHeadPath, userSex, userBirthday, personSignature, vitalityValue from imomo_clients where userId = ?";
        }
        String paras[] = { userEmail };

        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        if (rs.next()) {
            userInfo.put(MsgKeys.userId, rs.getString(1));
            userInfo.put(MsgKeys.userName, rs.getString(2));
            userInfo.put(MsgKeys.userHeadPath, rs.getString(3));
            userInfo.put(MsgKeys.userSex, rs.getString(4));
            userInfo.put(MsgKeys.userBirthday, rs.getString(5));
            userInfo.put(MsgKeys.personSignature, rs.getString(6));
            userInfo.put(MsgKeys.vitalityValue, rs.getInt(7));
        }
    } catch (Exception e) {
        userInfo = null;
        e.printStackTrace();
    } finally {
        sp.close();
    }
    return userInfo;
}

/**
 *          
 * 
 * @param userId
 * @return
 */
public boolean isTableExists(String tableName) {
    boolean isExists = true;
    String sql = "SHOW TABLES like ?";
    String paras[] = { tableName };
    SqlHelper sp = null;
    String tempTable = null;
    try {
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        if (!rs.next()) {
            isExists = false;
        }
    } catch (Exception e) {
        isExists = false;
        e.printStackTrace();
    } finally {
        sp.close();
    }
    return isExists;
}

/**
 *   Id
 * 
 * @param userEmail
 * @return
 */
public String allocateId() {
    SqlHelper sp = null;
    int newId = 0;
    try {
        String sql = "select allocate_id from allocation_id where flag = ?";
        String paras[] = { "0" };
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        if (rs.next()) {
            newId = rs.getInt(1);
            sp.updExecute(
                    "update allocation_id set flag = ? where flag = ?",
                    new String[] { "1", "0" });
            sp.updExecute("insert into allocation_id values(?,?)",
                    new String[] { (newId + 1) + "", "0" });
        } else {
            return "null";
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "null";
    } finally {
        sp.close();
    }
    return newId + "";
}

/**
 *         
 * 
 * @param msgDb
 * @return
 */
public boolean insertCacheMsg(MsgDb msgDb, String userId) {
    String sql = "insert into " + "mc_" + userId + " values (?,?)";
    String[] paras = { msgDb.msgType + "", msgDb.msgJson };
    return updateDb(sql, paras);
}

/**     ,          */
public boolean clearMsgCache(String userId) {
    String sql = "delete from " + "mc_" + userId + " where 1 = ?";
    String[] paras = { "1" };
    SqlHelper sqlHelper = new SqlHelper();
    return sqlHelper.updExecute(sql, paras);
}

/**
 *          (           ,    ,        )
 * 
 * @param userId
 *                   Id
 * @return   true    ,    
 */
public boolean createCacheTable(String userId) {
    String tableName = "mc_" + userId;//      
    String sql = "create table " + tableName
            + " (msgType int(4), msgJson text)";
    SqlHelper sqlHelper = new SqlHelper();
    return sqlHelper.create(sql);
}

/**
 *          
 * 
 * @param userId
 * @return
 */
public int getMsgCount(String userId) {
    int count = 0;// "SELECT count(*) FROM sqlite_master WHERE type='table' AND name= ? ";
    String tableName = "mc_" + userId;
    String sql = "select count(*) from " + tableName + " where 1 = ?";
    String paras[] = { "1" };
    SqlHelper sp = null;
    try {
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        if (rs.next()) {
            count = rs.getInt(1);
        }
    } catch (Exception e) {
        count = 0;
        e.printStackTrace();
    } finally {
        sp.close();
    }
    return count;
}

/**
 *           list
 * 
 * @param userId
 * @return
 */
public List<MsgDb> getCacheMsgs(String userId) {
    String tableName = "mc_" + userId;
    List<MsgDb> list = new ArrayList<MsgDb>();
    String sql = "select * from " + tableName + " where 1 = ?";
    String paras[] = { "1" };
    SqlHelper sp = null;
    try {
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        while (rs.next()) {
            MsgDb msgDb = new MsgDb();
            msgDb.msgType = rs.getInt("msgType");
            msgDb.msgJson = rs.getString("msgJson");
            list.add(msgDb);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sp.close();
    }

    return list;
}

/**
 *     
 * 
 * @param userId
 *              Id
 * @param friendId
 *                  Id
 * @return
 */
public boolean addFriend(String userId, String friendId) {
    SqlHelper sp = null;
    String sql2 = "select userId from friend_list  where userId = ?";
    String[] pp = { userId };
    try {
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql2, pp);
        if (!rs.next()) {
            System.out.println("rs.next() " + rs.next());
            String sql3 = "insert into friend_list(userId) values(?)";
            String paras[] = { userId };
            updateDb(sql3, paras);
        }
        String sql1 = "select friendList from friend_list  where userId = ?";
        String paras1[] = { userId };
        String freindListStr = "";
        sp = new SqlHelper();
        ResultSet rs2 = sp.query(sql1, paras1);
        if (rs2.next()) {
            freindListStr = rs2.getString(1);
        }
        if (freindListStr == null) {
            freindListStr = friendId;
        } else {
            String[] friends = getFriendIds(userId);
            boolean isExists = false;
            for (String string : friends) {
                if (string.equals(friendId)) {
                    isExists = true;
                    break;
                }
            }
            if (!isExists)
                freindListStr += "," + friendId;
        }

        String sql = "update friend_list set friendList = ? where userId = ?";
        String paras[] = { freindListStr, userId };
        return updateDb(sql, paras);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sp.close();
    }
    return false;

}

/**
 *     
 * 
 * @param userId
 * @param friendId
 * @return
 */
public boolean deleteFriend(String userId, String friendId) {
    String[] oldFriend = this.getFriendIds(userId);
    String newFriendStr = "";
    for (String str : oldFriend) {
        if (!str.equals(friendId)) {
            newFriendStr += str + ",";
        }
    }
    String sql = "update friend_list set friendList = ? where userId = ?";
    String paras[] = { newFriendStr.substring(0, newFriendStr.length() - 1), userId };
    return updateDb(sql, paras);
}

/**
 *       
 * 
 * @param userId
 * @return list
 */
public String[] getFriendIds(String userId) {
    String[] friendList = null;
    String sql = "select friendList from friend_list  where userId = ?";
    String paras[] = { userId };
    SqlHelper sp = null;
    try {
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql, paras);
        if (rs.next()) {
            friendList = rs.getString(1).split(",");
        }
    } catch (Exception e) {

//e.printStackTrace(); } finally { sp.close(); } return friendList; }
/**
 *      
 * @param userId
 * @param type
 * @return
 */
public boolean UpdateVitality(String userId, int type){
    SqlHelper sp = null;
    try {
        String sql1 = "select vitalityValue from imomo_clients where userId = ?";
        String[] paras1 = {userId};
        sp = new SqlHelper();
        ResultSet rs = sp.query(sql1, paras1);
        int vitalityValue = 0;
        if (rs.next()) {
            vitalityValue = rs.getInt(1);
        }
        String sql = "update imomo_clients set vitalityValue = ? where userId = ?";
        String[] paras = new String[2];
        if(type == -1){
            paras[0]= (vitalityValue - 10) + "";
        } else if(type == 1){
            paras[0]= (vitalityValue + 15) + "";
        }
        paras[1]=userId;
        return sp.updExecute(sql, paras);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sp.close();
    }
    return false;
}

}
파일 조작 클래스: 주요 방법은 바이너리 파일을 저장하고 그림이나 음성을 가져오는 바이트 그룹 패키지com입니다.server_utils;
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;
import com.imomo_server.ServerUtils;
/*** 병발성을 고려하여 * * @author Administrator * */public class FileTools {static FileTools fileTools;
public static void main(String[] args) {
    byte[] fff = FileTools.getInstance().getMultyFileBytes(
            StaticValues.MSG_CACHE_IMA_P_PATH + "fff.png");
    FileTools.getInstance().saveMultyFile(
            StaticValues.MSG_CACHE_IMA_P_PATH + "90joj.jpg", fff);
}

public static FileTools getInstance() {
    // if(fileTools == null){
    // fileTools = new FileTools();
    // }
    return new FileTools();
}

/**
 * @category            
 * @param msgBytes
 *                 byte  
 */
public void saveMultyFile(String filepath, byte[] msgBytes) {
    if (msgBytes.length > 0) {
        File file = new File(filepath);
        FileOutputStream fileout = null;
        FileChannel fc = null;
        try {
            fileout = new FileOutputStream(file);
            fc = fileout.getChannel();
            fileout.write(msgBytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fc.close();
                fileout.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    } else {
        System.out.println("  :    ,    !!");
    }
}

/**
 * @param filepath
 *                
 * @return      byte  
 */
public byte[] getMultyFileBytes(String filepath) {
    File file = new File(filepath);
    ByteBuffer bytebuffer = null;
    FileInputStream fileInputStream = null;
    FileChannel channel = null;
    try {
        if (!file.exists()) {
            System.err.println("      ...");
        } else {
            fileInputStream = new FileInputStream(file);
            channel = fileInputStream.getChannel();
            bytebuffer = ByteBuffer.allocate((int) channel.size());
            bytebuffer.clear();
            channel.read(bytebuffer);
            return bytebuffer.array();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            channel.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

/**
 *     
 * 
 * @param filePath
 *                
 */
public void deleteFile(String filePath) {
    File file = new File(filePath);
    if (file.exists()) {
        file.delete();
    }
}

/**
 *         
 * 
 * @param userId
 * @param reback
 */
public void saveReback(String userId, String reback) {
    File file = new File(StaticValues.REBACK_PATH);
    BufferedWriter out = null;
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(file, true)));
        out.write(userId + ":" + reback );//+ "\r
\r
" out.write("\r
"); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (Exception e) { e.printStackTrace(); } } }

}

좋은 웹페이지 즐겨찾기