欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sqlite在java项目中调用. sqlite

程序员文章站 2022-07-03 08:02:22
...

 

 sqlite工具数据库的操作:

 

package com.darkblue.dynem.util.sqlitedb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Logger;

import org.mortbay.util.Log;

import com.darkblue.dynem.test.TestEIMMainFrame;
import com.darkblue.dynem.util.filehelp.FileBean;

public class SqliteDB {
	private static final Logger log = Logger.getLogger(SqliteDB.class.toString());
	
	Connection conn;
    Statement stat;

    //连接到数据库
    public SqliteDB(){
        try {
            Class.forName("org.sqlite.JDBC");
            conn=DriverManager.getConnection("jdbc:sqlite:filebean.db");
            stat=conn.createStatement();
            log.info("连接到Sqlite");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //FileBean是在别处定义的类。作为例子使用。
    public FileBean readDB(){
        try {
            stat=conn.createStatement();
            ResultSet rs = stat.executeQuery("select * from ftable;");
            /*
            *将数据库中的数据读到一个byte数组中
            *通过ByteArrayInputStream传入ObjectInputStream中
            *从ObjectInputStream读出object对象并强制转换成Task
            */
            byte[] data=rs.getBytes(1);
            ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(data);
            ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);
            FileBean filebean=(FileBean)(objectInputStream.readObject());
            byteArrayInputStream.close();
            objectInputStream.close();
            rs.close();
            stat.close();
            conn.close();
            log.info("查询对象,关闭流 、sqlite数据库连接");
            return filebean;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    public void saveDB(FileBean filebean){
        try {
//            stat.executeUpdate("drop table if exists filetable;");
//            stat.executeUpdate("create table filetable (filetable);");
        	stat.executeUpdate("create table if not exists ftable(ftable);");
            PreparedStatement prep=conn.prepareStatement("insert into ftable values(?);");
            /*
            *使用ObjectOutputStream将对象序列化,
            *传入ByteArrayOutputStream中,
            *最后输出到一个byte类型的数组中
            *而这样的数组可以直接存入数据库
            */
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(arrayOutputStream);
            objectOutputStream.writeObject(filebean);
            objectOutputStream.flush();
            byte[] data=arrayOutputStream.toByteArray();
            prep.setBytes(1, data);
            prep.addBatch();
            arrayOutputStream.close();
            objectOutputStream.close();
            conn.setAutoCommit(false);
            prep.executeBatch();
            conn.setAutoCommit(true);
            stat.close();
            conn.close();
            log.info("数据保存,关闭流 、sqlite数据库连接");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
    	FileBean fBean =new SqliteDB().readDB();
    	System.out.println(fBean.getFilepath());
	}
    
}
}

实体类:

import java.io.Serializable;

/**
 * 发送消息列表
 * Created by Administrator on 2016/8/12.
 */
public class FileBean implements Serializable {
    public String id;
    public long filesize;//文件大小
    public String filename;//文件名字
    public String filepath;//文件路径
    public String filesource;//文件分享源


    public String getFilesource() {
        return filesource;
    }
    public void setFilesource(String filesource) {
        this.filesource = filesource;
    }
    public long getFilesize() {
        return filesize;
    }

    public void setFilesize(long filesize) {
        this.filesize = filesize;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getFilepath() {
        return filepath;
    }

    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    @Override
    public String toString() {
        return "FileBean{" +
                "id='" + id + '\'' +
                ", filesize=" + filesize +
                ", filename='" + filename + '\'' +
                ", filepath='" + filepath + '\'' +
                ", filesource='" + filesource + '\'' +
                '}';
    }

    public FileBean() {
    }


    public String toJsonString() {
        return "{\"id\":\"" + id + "\",\"filename\":\"" + filename + "\",\"filepath\":\"" + filepath + "\",\"filesize\":\"" + filesize + "\",\"filesource\":\"" + filesource + "\"}";
    }
}

 调用工具类:

package com.darkblue.dynem.util.filehelp;

import java.io.File;
import java.net.URI;
import java.sql.Connection;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import com.coolface.base.entity.NetworkChangeEvent;
import com.coolface.base.face.INetworkChangeListener;
import com.coolface.base.service.CoolfaceCoreManager;
import com.coolface.base.util.CoolfaceUtility;
import com.darkblue.dynem.util.sqlitedb.SQLiteJdbcUtils;
import com.darkblue.dynem.util.sqlitedb.SqliteDB;

import net.coolface.cloudnet.id.ID;
import net.coolface.cloudnet.id.IDFactory;

/**
 * Created by Houo on 2017/5/23.
 */

public class Fileutil {
    private static boolean isDirectory;

    public static boolean isDirectory(File file) {
        isDirectory = false;
        File[] fileArray = file.listFiles();
        if (fileArray.length > 0) {
            isDirectory = true;
        }
        return isDirectory;
    }

    /**
     * 文件夹文件排序
     *
     * @param files
     * @return
     */
    public static File[] sortFile(File[] files) {
        List<File> listfile = Arrays.asList(files);
        Collections.sort(listfile, new CustomComparator());   //按照指定的规则进行一个排序
        File[] array = listfile.toArray(new File[listfile.size()]);
        return array;
    }

    /**
     * 转换文件大小
     *
     * @param
     * @return
     */
    // 递归取得文件夹(包括子目录)中所有文件的大小
    public static long getFileSize(File f) throws Exception// 取得文件夹大小
    {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

//    public static String[] getFileName() {
//        File file = new File(path);
//        String[] fileName = file.list();
//        return fileName;
//    }
    public static List<String> getFileName(String path) {
        File f = new File(path);
        List<String> result = new ArrayList<String>();
        if (!f.exists()) {
         System.out.println("文件存储,路径不存在");
            return null;
        }
        
        
        File fa[] = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            File fs = fa[i];
            if (!fs.isDirectory()) {
                result.add(fs.getName());
                List<FileBean> files=new ArrayList<FileBean>();
                        FileBean file=new FileBean();
                        file.setId("share_Other" + (int) ((Math.random() * 9 + 1) * 100000));
                        file.setFilename(fs.getName());
                        file.setFilesize(fs.length());
                        file.setFilepath(fs.getAbsolutePath());
 //                       file.setFilesource(CommUtil.localPeerId+"");
                        file.setFilesource(CoolfaceCoreManager.instance().getPeergroup().getPeerID()+"");
                        files.add(file);
                       // SqliteUtils.sharefileDBManager.add(files);
                        new SqliteDB().saveDB(file);
                        
                       /*//1.建立数据库连接
                        try {
                        	SQLiteJdbcUtils sutil = new SQLiteJdbcUtils();
                        	 Connection conn = sutil.getConn("data.db");
                        	 conn.setAutoCommit(false);
                        	 Statement stat = conn.createStatement();
                        	 stat.executeUpdate( "create table if not exists filetable (id varchar(20), "
                        	 		+ "filesize long,filename varchar(20),filepath varchar(20),filesource "
                        	 		+ "varchar(20));" );//创建一个表
                        	 sutil.execute("");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}*/
            }
        }

        return result;
    }
    public static String[] getFileNames(List<String> filelist) {
        if(filelist!=null){
        String[] file = new String[filelist.size()];
        return filelist.toArray(file);
        }
        else {
            return null;
        }

    }


//    public static File[] FilesFilter(File[] files) {
//        for (int i = 0; i < files.length; i++) {
//            if (!files[i].isDirectory()) {
//                return files;
//            }
//        }
//        return files;
//    }
   
    
    
}

 调用方法:

 Fileutil.getFileName(file.getAbsolutePath());                //此处共享存至本地sqlite 方法调用

 

相关标签: sqlite