execsql.java

来自「java从文本文件中读取并执行SQL语句的示范。」· Java 代码 · 共 65 行

JAVA
65
字号
import java.io.*;
import java.util.*;
import java.sql.*;

class ExecSQL{
    
    public static void main(String[] args){
        try{
            Reader reader;
            if(args.length == 0){
                reader = new InputStreamReader(System.in);
            }else{
                reader = new FileReader(args[0]);
            }
            
	    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            Connection conn = getConnection();
            Statement stat = conn.createStatement();
            
            BufferedReader in = new BufferedReader(reader);
            
            boolean done = false;
            while(!done){
                if(args.length == 0){
                    System.out.print("输入命令");
                }
                String line = in.readLine();
                if(line == null || line.length() == 0){
                    done = true;
                }else{
                    try{
                        stat.execute(line);
                    }catch(SQLException ex){
                        while(ex != null){
                            ex.printStackTrace();
                            ex = ex.getNextException();
                        }
                    }
                }
            }
            in.close();
            stat.close();
            conn.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    public static Connection getConnection() throws SQLException, IOException{
        Properties props = new Properties();
        FileInputStream in = new FileInputStream("database.properties");
        props.load(in);
        in.close();
        
        String drivers = props.getProperty("driver");
        if(drivers != null){
            System.setProperty("drivers", drivers);
        }
        String url = props.getProperty("url");
        String username = props.getProperty("username");
        String password = props.getProperty("password");
        
        return DriverManager.getConnection(url, username, password);
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?