Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Выгрузка БД в текст файл при помощи Java 
:(
    Опции темы
asekeshka
Дата 11.6.2009, 07:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 8.6.2009

Репутация: нет
Всего: нет



Всем привет, хотелось бы что бы этот код выгружал базу в текстовый фаил. В данный момент он выгружает все в XML.

у когонить есть соображения что делать?

Код

public void run() {

        try {
            
            PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
            BufferedReader in = new BufferedReader(
            new InputStreamReader(
            socket.getInputStream(), streamCharset));

            String inputLine, outputLine = "";
            
            inputLine = in.readLine();
            
            AppRoot.writeDebug("Input request in thread " + hashCode() + " with input params " + inputLine);
            
            Pattern headerPattern = Pattern.compile("GET /(.*)\\?(.*) HTTP.*");
            Matcher m = headerPattern.matcher(inputLine);
            if(m.matches())
            {
                String strParams = m.group(2).trim();
                String funcName = m.group(1).trim();
                HashMap<String, String> queryMap = new HashMap<String, String>();
                
                StringTokenizer st = new StringTokenizer(strParams, "&");
                while (st.hasMoreTokens()) {
                    String str = st.nextToken();
                    String[] pair = str.split("=");
                    queryMap.put(pair[0], pair[1]);
                }
                
                if(funcName.equalsIgnoreCase("nop"))
                {
                    AppRoot.writeDebug("Nop func call in thread " + hashCode());
                    outputLine = "<response><version>1.02</version></response>";
                }
                else if(funcName.equalsIgnoreCase("ses_insp_state"))
                {
                    if(!queryMap.containsKey("rnn"))
                    {
                        outputLine = "<response><error>str param requared</error></response>";
                    }
                    else
                    {
                        String ob_rnn_search = java.net.URLDecoder.decode((queryMap.get("rnn")).toString());
                        
                        try {
                            Class.forName(
                            "net.sourceforge.jtds.jdbc.Driver");
                            //Class.forName("org.firebirdsql.jdbc.FBDriver"); //jdbc:firebirdsql://localhost/db_name
                            //Class.forName("net.sourceforge.jtds.jdbc.Driver"); //jdbc:sqlserver://localhost/db_name
                            Class.forName("interbase.interclient.Driver");
                            
                            // Параметры соединения с базой
                            Properties connInfo = new Properties();

                            connInfo.put("user", MicroServer.AppRoot.db_login);
                            connInfo.put("password", MicroServer.AppRoot.db_pass);
                            connInfo.put("charSet", "Cp1251");
                            
                            Connection cnn = DriverManager.getConnection(MicroServer.AppRoot.db_url, connInfo);
                            
                            Statement stat = cnn.createStatement();
                            ResultSet rs = stat.executeQuery(
                            "SELECT * " + " FROM * (\'" + ob_rnn_search + "\')");
                            outputLine = "<response>";
                            //"<table border=\"1\"><tr><th>RNN</th><th>Boss</th><th>Phone</th>" +
                            //    "<th>ID</th><th>Inspectation interval</th><th>Next inspectation date</th></tr>";
                            while (rs.next()) {
                                String ob_name = rs.getString(1);
                                String ob_adress = rs.getString(2);
                                String ob_state = rs.getString(3);
                                //int ob_id = rs.getInt(4);
                                //int ob_insp_int = rs.getInt(5);
                                //Date ob_cd  = rs.getDate(6);
                                
                                outputLine += "<object>";
                                outputLine += "<name>";
                                outputLine += ob_name;
                                outputLine += "</name>";
                                outputLine += "<adress>";
                                outputLine += ob_adress;
                                outputLine += "</adress>";
                                outputLine += "<state>";
                                outputLine += ob_state;
                                outputLine += "</state>";
                                outputLine += "</object>";
                            }
                            outputLine += "</response>";
                        } catch(Exception e) {
                            outputLine = "<p> ex " + e.getMessage() + " </p>";
                        }
                    }
                }
                else if(funcName.equalsIgnoreCase("ses_insp_int"))
                {
                    if(!queryMap.containsKey("rnn"))
                    {
                        outputLine = "<response><error>str param requared</error></response>";
                    }
                    else
                    {
                        String ob_rnn_search = java.net.URLDecoder.decode((queryMap.get("rnn")).toString());
                        
                        try {
                            Class.forName(
                            "net.sourceforge.jtds.jdbc.Driver");
                            //Class.forName("org.firebirdsql.jdbc.FBDriver"); //jdbc:firebirdsql://localhost/db_name
                            //Class.forName("net.sourceforge.jtds.jdbc.Driver"); //jdbc:sqlserver://localhost/db_name
                            Class.forName("interbase.interclient.Driver");
                            
                            // Параметры соединения с базой
                            Properties connInfo = new Properties();

                            connInfo.put("user", MicroServer.AppRoot.db_login);
                            connInfo.put("password", MicroServer.AppRoot.db_pass);
                            connInfo.put("charSet", "Cp1251");
                            
                            Connection cnn = DriverManager.getConnection(
                            MicroServer.AppRoot.db_url, connInfo);
                            
                            Statement stat = cnn.createStatement();
                            ResultSet rs = stat.executeQuery(
                            "SELECT OB_NAME, OB_ADRESS, OB_INSPECTION_INTERVAL " + 
                                " FROM ZAPROS_PERIOD(\'" + ob_rnn_search + "\')");
                            outputLine = "<response>";
                            //"<table border=\"1\"><tr><th>RNN</th><th>Boss</th><th>Phone</th>" +
                            //    "<th>ID</th><th>Inspectation interval</th><th>Next inspectation date</th></tr>";
                            while (rs.next()) {
                                String ob_name = rs.getString(1);
                                String ob_adress = rs.getString(2);
                                String ob_interval = rs.getString(3);
                                //int ob_id = rs.getInt(4);
                                //int ob_insp_int = rs.getInt(5);
                                //Date ob_cd  = rs.getDate(6);
                                
                                outputLine += "<object>";
                                outputLine += "<name>";
                                outputLine += ob_name;
                                outputLine += "</name>";
                                outputLine += "<adress>";
                                outputLine += ob_adress;
                                outputLine += "</adress>";
                                outputLine += "<interval>";
                                outputLine += ob_interval;
                                outputLine += "</interval>";
                                outputLine += "</object>";
                            }
                            outputLine += "</response>";
                        } catch(Exception e) {
                            outputLine = "<p> ex " + e.getMessage() + " </p>";
                        }
                    }
                }
                else if(funcName.equalsIgnoreCase("econ_dem_state"))
                {
                    if(!queryMap.containsKey("dc") && (!queryMap.containsKey("drn") || !queryMap.containsKey("drd")))
                    {
                        outputLine = "<response><error>Demand Code or RegNumber|RegDate param requared</error></response>";
                    }
                    else
                    {
                        String ob_dc_search = "NULL";
                        String ob_drn_search = "NULL";
                        String ob_drd_search = "NULL";
                        
                        if(queryMap.containsKey("dc"))
                            ob_dc_search = "N\'"+java.net.URLDecoder.decode((queryMap.get("dc")).toString())+"\'";
                        if(queryMap.containsKey("drn"))
                            ob_drn_search = "\'"+java.net.URLDecoder.decode((queryMap.get("drn")).toString())+"\'";
                        if(queryMap.containsKey("drd"))
                            ob_drd_search = "\'"+java.net.URLDecoder.decode((queryMap.get("drd")).toString())+"\'";
                        
                        AppRoot.writeDebug("Input request in thread " + hashCode() + " with input db-params " + 
                            ob_dc_search + ", " + ob_drn_search + ", " + ob_drd_search);
                        
                        try {
                            Class.forName(
                            "net.sourceforge.jtds.jdbc.Driver");
                            //Class.forName("org.firebirdsql.jdbc.FBDriver"); //jdbc:firebirdsql://localhost/db_name
                            //Class.forName("net.sourceforge.jtds.jdbc.Driver"); //jdbc:sqlserver://localhost/db_name
                            //Class.forName("interbase.interclient.Driver");
                            
                            // Параметры соединения с базой
                            Properties connInfo = new Properties();

                            connInfo.put("user", MicroServer.AppRoot.db_login);
                            connInfo.put("password", MicroServer.AppRoot.db_pass);
                            connInfo.put("charSet", "Cp1251");
                            
                            Connection cnn = DriverManager.getConnection(
                            MicroServer.AppRoot.db_url, connInfo);
                            
                            Statement stat = cnn.createStatement();
                            ResultSet rs = stat.executeQuery(
                            "DECLARE    @return_value int, "+
        "@iError int, "+
        "@vcErrorText varchar(256), "+
        "@vcDemandState varchar(128) "+

"EXEC    @return_value = [dbo].[pGetLastDemandState] "+
        "@vcDemandCode = " + ob_dc_search + ","+
        "@vcDemandRegNumber = " + ob_drn_search + ","+
        "@vcDemandRegDate = " + ob_drn_search + ","+
        "@bGetKZ = 1,"+
        "@iError = @iError OUTPUT,"+
        "@vcErrorText = @vcErrorText OUTPUT,"+
        "@vcDemandState = @vcDemandState OUTPUT   "+

"SELECT    @iError as N'@iError',"+
        "@vcErrorText as N'@vcErrorText',"+
        "@vcDemandState as N'@vcDemandState'   "+

"SELECT    \'Return Value\' = @return_value");
                            outputLine = "<response>";
                            //"<table border=\"1\"><tr><th>RNN</th><th>Boss</th><th>Phone</th>" +
                            //    "<th>ID</th><th>Inspectation interval</th><th>Next inspectation date</th></tr>";
                            while (rs.next()) {
                                String ob_er_state = rs.getString(1);
                                String ob_error = rs.getString(2);
                                String ob_state = rs.getString(3);
                                //int ob_id = rs.getInt(4);
                                //int ob_insp_int = rs.getInt(5);
                                //Date ob_cd  = rs.getDate(6);
                                
                                outputLine += "<object>";
                                outputLine += "<er_num>";
                                outputLine += ob_er_state;
                                outputLine += "</er_num>";
                                outputLine += "<error>";
                                outputLine += ob_error;
                                outputLine += "</error>";
                                outputLine += "<state>";
                                outputLine += ob_state;
                                outputLine += "</state>";
                                outputLine += "</object>";
                            }
                            outputLine += "</response>";
                        } catch(Exception e) {
                            outputLine = "<p> ex " + e.getMessage() + " </p>";
                        }
                    }
                }
                else
                {
                    outputLine = "<p> No such func:" + funcName + " </p>";
                    AppRoot.writeDebug("No such func:" + funcName + " in thread " + hashCode());
                }
            }
            else
            {
                outputLine = "<p> Bad query string: " + inputLine + "</p>";
                AppRoot.writeDebug("Bad query string: " + inputLine + " in thread " + hashCode());
            }
            
            AppRoot.writeDebug("Out data in thread " + hashCode() + ": " + outputLine);
            
            out.println("HTTP/1.0 200 Ok");
            out.println("Content-Type: text/xml");
            out.println("Content-Length: " + outputLine.length());
            out.println("Connection: close\n\n\n");
            out.println(outputLine);
            
            AppRoot.writeDebug("Request served in thread " + hashCode());

            out.close();
            in.close();
            socket.close();

        } catch (Exception e) {
            System.err.println("Cleint hooked up, reason: " + e.getMessage());
            AppRoot.writeDebug("Cleint hooked up, reason: " + e.getMessage() + " in thread " + hashCode());
        }
    }

PM MAIL   Вверх
LSD
Дата 11.6.2009, 11:25 (ссылка) |    (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Leprechaun Software Developer
****


Профиль
Группа: Модератор
Сообщений: 15718
Регистрация: 24.3.2004
Где: Dublin

Репутация: 210
Всего: 538



Код

stat.executeQuery("SELECT * " + " FROM * (\'" + ob_rnn_search + "\')");

Жесть smile 



Цитата(asekeshka @  11.6.2009,  07:46 Найти цитируемый пост)
у когонить есть соображения что делать?

Я бы предложил заплатить программисту, чтобы тот написал нужный код.


--------------------
Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it.
PM MAIL WWW   Вверх
hamsterKSU
Дата 11.6.2009, 17:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 401
Регистрация: 20.10.2006
Где: Украина, Херсон

Репутация: 1
Всего: 11



да, надо перписать код smile
юзаем либу для создания CSV файлика и все нормально. например javacsv или openscv.
выбераем данные и записываем их в файл


PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.2839 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.