解密陌生人(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();
    }
}

}

具体业务逻辑,model层,根据需要添加相应的方法,以下包括注册、登录、找回密码、添加好友、保存或获取离线消息等

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 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;
}

}

文件操作类: 主要的方法是保存二进制文件、获取图片或语音的字节数组

package 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\n\r\n"
        out.write("\r\n");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

}

时间: 2024-10-15 12:18:57

解密陌生人(6)数据库操作工具和文件操作类的相关文章

C#封装的常用文件操作类实例

本文实例讲述了C#封装的常用文件操作类.分享给大家供大家参考.具体如下: 这个C#类封装了我们经常能用到的文件操作方法,包括读写文件.获取文件扩展名.复制文件.追加内容到文件.删除文件.移动文件.创建目录.递归删除文件及目录.列目录.列文件等,不可多得. using System; using System.Text; using System.Web; using System.IO; namespace DotNet.Utilities { public class FileOperate

C#使用iTextSharp封装的PDF文件操作类实例

本文实例讲述了C#使用iTextSharp封装的PDF文件操作类.分享给大家供大家参考.具体分析如下: 这个C#代码主要讲iTextSharp中用于操作PDF文件的方法进行了再次封装,可以更加方便的访问PDF文档,可以动态生成PDF文件.添加内容.设置段落.设置字体等. using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; namespace DotNet.Utilities { /// <summary> ///

File 文件操作类 大全

File  文件操作类  大全 许多人都会对文件操作感到很难  我也是  但是一个好的项目中必定会涉及到文件操作的 文件的复制 粘贴  等等等 公司大佬写了 一个文件操作的工具类 感觉还是棒棒的啦   代码如下 : 1 /** 2 * Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. 3 */ 4 package

C# 文件操作类

using System;using System.IO; namespace Utils{ public class IOHelper { public IOHelper(); public static bool CopyDir(DirectoryInfo fromDir, string toDir); //复制目录 public static bool CopyDir(string fromDir, string toDir); //复制目录 public static bool Crea

dedecms中提取的zip压缩文件操作类zip.class.php

从织梦DeDeCMS中提取的zip压缩文件操作类,包含zip文件压缩.解压缩.添加文件到压缩包中等多个实用的函数,注释详细方便使用. 下载:dedecms中提取的zip压缩文件操作类zip.class.php 包含的函数和简单的使用方法: 1.函数get_List($zip_name) ,函数作用:获取zip文件中的文件列表.函数参数 $zip_name  zip文件名.返回值 文件列表数组. 2.函数Add($files,$compact),函数作用:增加文件到压缩文件.函数参数 $files

[C#] 常用工具类——文件操作类

/// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在</para> /// <para> IsImgFilename:判断文件名是否为浏览器可以直接显示的图片文件名</para> /// <para> CopyFiles:复制指定目录的所有文件</para> /// <para> MoveFi

asp.net文件操作类

/** 文件操作类 **/ #region 引用命名空间 using System; using System.Collections.Generic; using System.Text; using System.IO; #endregion namespace CommonUtilities { /// <summary> /// 文件操作类 /// </summary> public class FileHelper { #region 检测指定目录是否存在 /// <

【文件操作类】史上最完整的文件和目录操作类

using System; using System.Text; using System.IO; namespace HelloCsharp.Utilities { /// <summary> /// 文件操作类 /// </summary> public static class DirFile { #region 检测指定目录是否存在 /// <summary> /// 检测指定目录是否存在 /// </summary> /// <param n

php对数据库增删改查操作类

1 <?php 2 3 /** 4 * 函数名称:SqlTool.class.php 5 * 函数功能:php对数据库增删改查操作类 6 * 函数作者:张真贵 7 * 创建时间:2015-01-05 8 * 修改时间: 9 */ 10 header("Content-Type:text/html;charset=utf-8"); 11 class SqlTool{ 12 private $conn; 13 private $host = 'localhost'; 14 priva