Deciphering strangers (6) Database operations tools and file manipulation classes

Source: Internet
Author: User

Tip: Because the project is a little bit large for me personally, so may be in some aspects of unclear or logic is not strong enough, if there is a problem please timely @ me.
Original project: https://github.com/LineChen/

Introduce the database operation class and the file operation class before specifying the operation.
Database: MySQL, MVC mode
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;

Connection Database 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;}    /** Create a database or a new table */public boolean create (String sql) {Boolean isOk = true;        try {connectdb ();        PS = ct.preparestatement (SQL);        IsOk =!ps.execute ();//Returns a Boolean value that returns false for success and vice versa} catch (Exception e) {isOk = false;    E.printstacktrace ();    } finally {this.close (); } return isOk;}        /** Queries */public ResultSet query (String SQL, string[] paras) {try {connectdb ();        PS = ct.preparestatement (SQL);        Assign values to parameters for (int i = 0; i < paras.length; i++) {ps.setstring (i + 1, paras[i]);    } rs = Ps.executequery ();    } catch (Exception e) {e.printstacktrace (); } return RS;} /** Delete and change */public Boolean updExecute (String SQL, string[] paras) {Boolean b = true;        try {connectdb ();        PS = ct.preparestatement (SQL); For PS?        Assignment for (int i = 0; i < paras.length; i++) {ps.setstring (i + 1, paras[i]);        } ps.executeupdate ()///Execute operation returns the number of rows//if (ps.executeupdate () = 1) {//b = false;        }} catch (Exception e) {b = false;    E.printstacktrace ();    } finally {this.close (); } return B;        Unified Close Resource public void close () {try {if (rs! = null) rs.close ();        if (PS! = null) ps.close ();    if (ct! = null) ct.close ();    } catch (Exception e) {e.printstacktrace (); }}

}

Specific business logic, model layer, according to the need to add the appropriate method, the following include registration, login, retrieve password, add friends, save or get offline messages, etc.

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 {
/* Add user, modify information and other actions /
public boolean updatedb (String sql, string[] paras) {
Create SqlHelper (if the program concurrency is not considered, you can sqlhelper make static)
SqlHelper SqlHelper = new SqlHelper ();
return Sqlhelper.updexecute (SQL, paras);
}

/** Login Authentication */public boolean checkUser (String useremail, String userpasswd) {SqlHelper sp = null;    Boolean islegal = false;        try {//block SQL statement and argument list 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;}  /** * Returns user name based on ID * * @param userId * @return return null means that the user */public string GetUserName (String UserEmail, Boolean isemail) is not present    {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 * User registered mailbox or user ID * @param isemail * is mailbox or user ID true-mailbox false-User ID * @re    Turn */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, Personsignatur E, 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;} /** * Determine if a table exists * * @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;}    /** * Assign 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 + "";} /** * Insert an offline message * * @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);} /** the information in the table is cached based on the table name */public boolean clearmsgcache (String userId) {String sql = "Delete from" + "MC_" + userId + "whe    Re 1 =? ";    String[] Paras = {"1"};    SqlHelper SqlHelper = new SqlHelper (); return Sqlhelper.updexecute (SQL, paras);} /** * Create a user message buffer table (when the user receiving the message is not online, staging the message, sending it immediately after online) * * @param userId * User ID to receive information * @return return True to indicate success and vice versa */public bo Olean createcachetable (String userId) {string tableName = "MC_" + userid;//indicates as short as possible String sql = "CREATE TABLE" + TA    Blename + "(msgtype int (4), Msgjson text)";    SqlHelper SqlHelper = new SqlHelper (); return sqlhelper.create (SQL);} /** * Get offline message record number * * @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;} /** * Get offline message from Database List * * @param userId * @return */public list<msgdb> getcachemsgs (string userid) {string table    Name = "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;} /** * Add friend * @param userId * User ID * @param friendid * Friend ID to add * @return */public boolean Addfrie    nd (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;} /** * Delete friend * @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);} /** * Get Friends List * * @param userId * @return list */public string[] Getfriendids (String userId) {string[] friendlist = Nu    ll    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;}

}

File Operation class: The Main method is to save the binary file, get the picture or the voice of the byte array
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;

/**
* Consider concurrency,
*
* @author Administrator
*
*/
public class Filetools {
Static Filetools Filetools;

public static void Main (string[] args) {byte[] fff = filetools.getinstance (). Getmultyfilebytes (Staticvalue    S.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 Store user picture or voice message * @param msgbytes * picture or voice byte array */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 ("Warning: file is empty, cannot save!!"); }}/** * @param filepath * file path * @return picture or Voice byte array */public byte[] getmultyfilebytes (String filepath) {Fi    Le file = new file (filepath);    Bytebuffer bytebuffer = null;    FileInputStream fileinputstream = null;    FileChannel channel = null;        try {if (!file.exists ()) {System.err.println ("The file does not exist ...");            } 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; /** * Delete File * * @param filePath * file path */public void DeleteFile (String filePath) {File File = new file    Path);    if (file.exists ()) {file.delete (); }}/** * Save User feedback * * @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 (); }    }}

}

Deciphering strangers (6) Database operations tools and file manipulation classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.