欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

jdbc连接sqlite数据库,,本简单工具共2个类,每个

来源: javaer 分享于  点击 41180 次 点评:237

jdbc连接sqlite数据库,,本简单工具共2个类,每个


本简单工具共2个类,每个类,没有实现事务,需要的可以改造下,很方便了 ,主类Main和连接管理类connControl 还有个自己实现的国际化类的Message类还有3个properties文件,分别是message_zh_CN.properties和message_en_US.properties最后一个默认的message_default.properties,当然,我们要操作sqlite需要用到sqlite相应的jar包 ,我这使用的是sqlite-jdbc-3.7.2.jar最新的,大家可以到官网下载

[Java]代码

package org.open2all.jsqlite;import java.sql.ResultSetMetaData;import java.sql.Statement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Scanner;import org.open2all.jsqlite.conn.ConnControl;public class Main {    private static ConnControl connControl = null;    private static Statement statememt = null;    public static void main(String[] args) {        Scanner input=new Scanner(System.in);        if(args.length>0) {            String fileName = args[0];            connControl= new ConnControl(fileName);            do {                System.out.println(Message.MSG_1);                String sqlText = input.nextLine();                if("exit".equals(sqlText) || "exit;".equals(sqlText)) {                    connControl.close();                    System.out.println(Message.MSG_2);                    break;                }                if(!doWrok(sqlText))                    break;            } while(true);        } else {            System.out.println(Message.MSG_3);        }        input.close();        connControl.close();    }    private static boolean doWrok(String inputText) {        boolean flag =true;        //允许同时执行多条语句,用;号分开        String[] sqls = inputText.split(";");        if(connControl.open()) {            statememt = connControl.getStatememt();            for(String sql : sqls) {                //如果sql语句是空的,则跳过执行下一条                sql = sql.trim();                if("".equals(sql))                    continue;                if(sql.startsWith("insert")||sql.startsWith("delete")||                        sql.startsWith("update")||sql.startsWith("create")                        ||sql.startsWith("drop")) {                    int count=0;                    try {                        count = statememt.executeUpdate(sql);                    } catch (SQLException e) {                        System.out.println(Message.MSG_4+e.getMessage());                    }                     String printStr="";                    if(sql.startsWith("create")) {                        printStr = Message.MSG_5;                    } else if(sql.startsWith("drop")) {                        printStr = Message.MSG_6;                    } else {                        printStr = Message.MSG_7+count;                    }                    System.out.println(printStr);                } else if( sql.startsWith("select")){                    doSelect(sql);                } else if(sql.equals("show tables")) {                    //利用类似mysql的命令语句查询出数据库文件中所有的表                    doSelect("select name as tableName from sqlite_master where type='table' order by name");                }                else {                    try {                        statememt.execute(sql);                        System.out.println(Message.MSG_8);                    } catch (SQLException e) {                        System.out.println(Message.MSG_4+e.getMessage());                    }                }            }        } else {            System.out.println(Message.MSG_9);            flag = false;        }        return flag;    }    private static void doSelect(String sql) {        ResultSet rs=null;        try {            rs = statememt.executeQuery(sql);            ResultSetMetaData  rsmd = rs.getMetaData();            int columnCount = rsmd.getColumnCount();            String[] columns = new String[columnCount];            System.out.println(Message.MSG_10);            for(int i=1;i<=columnCount;i++){                columns[i-1] = rsmd.getColumnLabel(i);                System.out.print(columns[i-1]+"\t|\t");            }            System.out.println();            while(rs.next()) {                for(int i=1;i<=columnCount;i++) {                    System.out.print(rs.getString(i)+"\t|\t");                }                System.out.println();            }            rs.close();        } catch (SQLException e) {            System.out.println(Message.MSG_4+e.getMessage());        }    }}

[Java]代码

package org.open2all.jsqlite.conn;import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;public class ConnControl {    private Connection conn;    private Statement statememt;    private String fileName;    private boolean isConnected;    /**     * 获取Statement     * @return     */    public Statement getStatememt()    {        return statememt;    }    public boolean isConnected() {        return isConnected;    }    public ConnControl(String fileName) {        this.fileName = fileName;    }    private void getConnection() throws Exception{        try{            Class.forName("org.sqlite.JDBC");            conn=DriverManager.getConnection("jdbc:sqlite:"+fileName);            statememt = conn.createStatement();            isConnected=true;        } catch(Exception e) {            e.printStackTrace();            close();            throw e;        }    }    public boolean open() {        if(isConnected)            return isConnected; //已经有连接上了,不需要重复连接        else {            try {                close();    //先关闭一次                getConnection();            } catch (Exception e) {                e.printStackTrace();            }        }        return isConnected;    }    public void close() {        if(statememt!=null) {            try {                statememt.close();                statememt=null;            } catch(Exception e) {            }        }        if(conn!=null && isConnected) {            try {                conn.close();                isConnected=false;                conn=null;            } catch(Exception e) {            }        }    }}

[Java]代码

package org.open2all.jsqlite;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.Field;import java.util.Enumeration;import java.util.Locale;import java.util.Properties;public class Message {    static {        //获取当前Java虚拟机线程默认的国家和语言信息        Locale defaultLocale = Locale.getDefault();        String country = defaultLocale.getCountry();//返回国家地区代码        String language = defaultLocale.getLanguage();//返回国家的语言        String propFileName = "message";        propFileName = propFileName+"_"+language+"_"+country+".properties";        try {            fillData(propFileName);        } catch (IOException e) {            System.out.println("Fail to load the properties file!try to reload the default properties file : "+e.getMessage());            propFileName = "message_default.properties";            try {                fillData(propFileName);            } catch (IOException e1) {                System.out.println("Fail to load the properties file ! the app have to exit : "+e1.getMessage());                System.exit(-1);            }        }    }    public static String MSG_1;    public static String MSG_2;    public static String MSG_3;    public static String MSG_4;    public static String MSG_5;    public static String MSG_6;    public static String MSG_7;    public static String MSG_8;    public static String MSG_9;    public static String MSG_10;    private static void fillData(String propFileName) throws IOException {        InputStream in = ClassLoader.getSystemResourceAsStream(propFileName);        Properties pros = new Properties();        pros.load(in);        Enumeration<String> en =(Enumeration<String>) pros.propertyNames();//得到资源文件中的所有key值        while (en.hasMoreElements()) {              String key = en.nextElement();              String value = pros.getProperty(key);            Field[] fields = Message.class.getFields();            for(Field field : fields) {                if(key.equals(field.getName())) {                    try {                        field.set(null, value);                    } catch(Exception e) {                        System.out.println("初始化国际文件出错:"+e.getMessage());                    }                    break;                }            }        }        pros.clear();        in.close();    }}

[其他]代码

#message_default.propertiesMSG_1=Please input the command:MSG_2=Thanks to use jsqliteMSG_3=Please input the sqlite fileNameMSG_4=Fail to execute the sqlMSG_5=Create table successMSG_6=Drop table successMSG_7=Effected rows:MSG_8=Execute successMSG_9=Fail to open sqlite FileMSG_10=The resultSet:#message_en_US.propertiesMSG_1=Please input the command:MSG_2=Thanks to use jsqliteMSG_3=Please input the sqlite fileNameMSG_4=Fail to execute the sqlMSG_5=Create table successMSG_6=Drop table successMSG_7=Effected rows:MSG_8=Execute successMSG_9=Fail to open sqlite FileMSG_10=The resultSet:#message_zh_CN.propertiesMSG_1=请输入要执行的命令:MSG_2=欢迎下次使用MSG_3=请输入sqlite数据库名MSG_4=执行sql语句出错:MSG_5=创建成功MSG_6=删除成功MSG_7=受影响的行数:MSG_8=执行成功MSG_9=打开数据库文件出错!MSG_10=查询结果:
相关栏目:

用户点评