Tuesday, 8 December 2015

java code


import java.sql.DatabaseMetaData;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.*;
import java.util.*;
/**
 * This class connects to a database and dumps all the tables and contents out to stdout in the form of
 * a set of SQL executable statements
 */
public class Oracle2sql {

public static List<String> insList=new ArrayList<String>();
    /** Dump the whole database to an SQL string */
    public static String dumpDB(Properties props) {
        String driverClassName = props.getProperty("driver.class");
        String driverURL = props.getProperty("driver.url");
        System.out.println("driverClassName:"+driverClassName);
System.out.println("driver.url:"+driverURL);
// Default to not having a quote character
        String columnNameQuote = props.getProperty("columnName.quoteChar", "");
        DatabaseMetaData dbMetaData = null;
        Connection dbConn = null;
    //    StringBuffer result=null;
try {
            Class.forName(driverClassName);
            dbConn = DriverManager.getConnection(driverURL, props);
   System.out.println("DB Connection Established.");
            dbMetaData = dbConn.getMetaData();
        }
        catch( Exception e ) {
            System.err.println("Unable to connect to database: "+e);
            return null;
        }

        try {
  //          result = new StringBuffer();
            String catalog = props.getProperty("catalog");
            String schema = props.getProperty("schemaPattern");
            String tables = props.getProperty("tableName");
            ResultSet rs = dbMetaData.getTables(catalog, schema, tables, null);
            if (! rs.next()) {
                System.out.println("Unable to find any tables matching: catalog="+catalog+" schema="+schema+" tables="+tables);
                rs.close();
            } else {
System.out.println("catalog:"+catalog+" schema:"+schema+" tables:"+tables);
                // Right, we have some tables, so we can go to work.
                // the details we have are
                // TABLE_CAT String => table catalog (may be null)
                // TABLE_SCHEM String => table schema (may be null)
                // TABLE_NAME String => table name
                // TABLE_TYPE String => table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
                // REMARKS String => explanatory comment on the table
                // TYPE_CAT String => the types catalog (may be null)
                // TYPE_SCHEM String => the types schema (may be null)
                // TYPE_NAME String => type name (may be null)
                // SELF_REFERENCING_COL_NAME String => name of the designated "identifier" column of a typed table (may be null)
                // REF_GENERATION String => specifies how values in SELF_REFERENCING_COL_NAME are created. Values are "SYSTEM", "USER", "DERIVED". (may be null)
                // We will ignore the schema and stuff, because people might want to import it somewhere else
                // We will also ignore any tables that aren't of type TABLE for now.
                // We use a do-while because we've already caled rs.next to see if there are any rows
                do {
                    String tableName = rs.getString("TABLE_NAME");
                    String tableType = rs.getString("TABLE_TYPE");

           if ("TABLE".equalsIgnoreCase(tableType)&& "CHANNEL_MASTER_VIEW,PACKAGE_MASTER_VIEW,PACKAGE_CHANNEL_MAP_VIEW,LANGUAGE_MASTER,VIEW_CATEGORY_MASTER,VIEW_SUBCAT_MASTER,VIEW_VOD_MASTER,VOD_METADATA,SONY_LIV_IMAGE,ASSETS_URL_DETAILS,CLIENT_WEB_URL".contains(tableName)) {
// if ("TABLE".equalsIgnoreCase(tableType)&& "PACKAGE_CHANNEL_MAP_VIEW".contains(tableName)) {
System.out.println("tablename ="+tableName+"] and tableType="+tableType);
                        //result.append("\n\n-- "+tableName);
                        //result.append("\nCREATE TABLE "+tableName+" (\n");
                        ResultSet tableMetaData = dbMetaData.getColumns(null, null, tableName, "%");
                        boolean firstLine = true;
                        while (tableMetaData.next()) {
                            if (firstLine) {
                                firstLine = false;
                            } else {
                                // If we're not the first line, then finish the previous line with a comma
                          //      result.append(",\n");
                            }
                            String columnName = tableMetaData.getString("COLUMN_NAME");
                            String columnType = tableMetaData.getString("TYPE_NAME");
                            // WARNING: this may give daft answers for some types on some databases (eg JDBC-ODBC link)
                            int columnSize = tableMetaData.getInt("COLUMN_SIZE");
                            String nullable = tableMetaData.getString("IS_NULLABLE");
                            String nullString = "NULL";
                            if ("NO".equalsIgnoreCase(nullable)) {
                                nullString = "NOT NULL";
                            }
//System.out.println("columnName :: "+columnName+"  :: columnType :: "+columnType);
                            //result.append("    "+columnNameQuote+columnName+columnNameQuote+" "+columnType+" ("+columnSize+")"+" "+nullString);
                        }
                        tableMetaData.close();

                        // Now we need to put the primary key constraint
                        try {
                            ResultSet primaryKeys = dbMetaData.getPrimaryKeys(catalog, schema, tableName);
                            // What we might get:
                            // TABLE_CAT String => table catalog (may be null)
                            // TABLE_SCHEM String => table schema (may be null)
                            // TABLE_NAME String => table name
                            // COLUMN_NAME String => column name
                            // KEY_SEQ short => sequence number within primary key
                            // PK_NAME String => primary key name (may be null)
                            String primaryKeyName = null;
                            StringBuffer primaryKeyColumns = new StringBuffer();
                            while (primaryKeys.next()) {
                                String thisKeyName = primaryKeys.getString("PK_NAME");
                                if ((thisKeyName != null && primaryKeyName == null)
                                        || (thisKeyName == null && primaryKeyName != null)
                                        || (thisKeyName != null && ! thisKeyName.equals(primaryKeyName))
                                        || (primaryKeyName != null && ! primaryKeyName.equals(thisKeyName))) {
                                    // the keynames aren't the same, so output all that we have so far (if anything)
                                    // and start a new primary key entry
                                    if (primaryKeyColumns.length() > 0) {
                                        // There's something to output
                                       // result.append(",\n    PRIMARY KEY ");
                                        if (primaryKeyName != null) {
//result.append(primaryKeyName);
}
                                       // result.append("("+primaryKeyColumns.toString()+")");
                                    }
                                    // Start again with the new name
                                    primaryKeyColumns = new StringBuffer();
                                    primaryKeyName = thisKeyName;
                                }
                                // Now append the column
                                if (primaryKeyColumns.length() > 0) {
                                    primaryKeyColumns.append(", ");
                                }
                                primaryKeyColumns.append(primaryKeys.getString("COLUMN_NAME"));
                            }
                            if (primaryKeyColumns.length() > 0) {
                                // There's something to output
                               // result.append(",\n    PRIMARY KEY ");
                                if (primaryKeyName != null) {
//result.append(primaryKeyName);
}
                                //result.append(" ("+primaryKeyColumns.toString()+")");
                            }
                        } catch (SQLException e) {
                            // NB you will get this exception with the JDBC-ODBC link because it says
                            // [Microsoft][ODBC Driver Manager] Driver does not support this function
                            System.err.println("Unable to get primary keys for table "+tableName+" because "+e);
                        }

                        //result.append("\n);\n");
                        // Right, we have a table, so we can go and dump it

// System.out.println("RESULT ["+result.toString()+"]");
                        dumpTable(dbConn,tableName);
                    }
                } while (rs.next());
                rs.close();
            }
            dbConn.close();
//            return result.toString();
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }finally{
// result=null;
}
        return null;
    }

    /** dump this particular table to the string buffer */
    private static void dumpTable(Connection dbConn,String tableName) {
       // StringBuffer result=new StringBuffer();
try {
        // System.out.println("Inside dumpTable: TableName="+tableName);  
// First we output the create table stuff
            PreparedStatement stmt = dbConn.prepareStatement("SELECT * FROM "+tableName);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            // Now we can output the actual data
//            result.append("\n\n-- Data for "+tableName+"\n");
        while (rs.next()) {
StringBuffer result=new StringBuffer();
if(tableName.equals("PACKAGE_CHANNEL_MAP_VIEW")){
result.append("INSERT INTO PACKAGE_CHANNEL_MAP_VIEW_REMOTE VALUES (");
}else if(tableName.equals("VOD_METADATA")){
result.append("INSERT INTO VOD_METADATA_REMOTE VALUES (");
}else if(tableName.equals("CLIENT_WEB_URL")){
result.append("INSERT INTO CLIENT_WEB_URL_REMOTE VALUES (");
}else if(tableName.equals("PACKAGE_MASTER_VIEW")){
result.append("INSERT INTO PACKAGE_MASTER_VIEW_REMOTE VALUES (");
}else if(tableName.equals("LANGUAGE_MASTER")){
result.append("INSERT INTO LANGUAGE_MASTER_REMOTE VALUES (");
} else {
result.append("INSERT INTO "+tableName+" VALUES (");
}
                for (int i=0; i<columnCount; i++) {
                    if (i > 0) {
                        result.append(", ");
                    }
                    Object value = rs.getObject(i+1);
                    if (value == null) {
                        result.append("NULL");
                    } else {
                        String outputValue = value.toString();

                        outputValue = outputValue.replaceAll("'","''");
                        result.append("'"+outputValue+"'");
                    }
                }
                result.append(");\n");
//result.append(");");
//if(tableName.equals("VIEW_CATEGORY_MASTER"))
//System.out.println("RESULT ["+result.toString()+"]");
insList.add(result.toString());
result=null;
        }


//System.err.println("list size--------- "+insList.size());
//            result=null;
rs.close();
stmt.close();
        } catch (SQLException e) {
            System.err.println("Unable to dump table "+tableName+" because: "+e);
        }finally{
//if(result!=null)result=null;
}
    }

    public static void batchInsert(List iList){
System.out.println("batchInsert -----iList @@@@@"+iList.size());
    Connection mySqlConn = null;
    Statement st=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            mySqlConn = DriverManager.getConnection("jdbc:mysql://172.31.22.59:3306/unified","neo", "admin123");
            if(mySqlConn!=null){
            mySqlConn.setAutoCommit(false);// Disables auto-commit.
            st = mySqlConn.createStatement();

st.addBatch("TRUNCATE TABLE CHANNEL_MASTER_VIEW;");
st.addBatch("TRUNCATE TABLE PACKAGE_MASTER_VIEW_REMOTE;");

 st.addBatch("TRUNCATE TABLE PACKAGE_CHANNEL_MAP_VIEW_REMOTE;");
st.addBatch("TRUNCATE TABLE LANGUAGE_MASTER_REMOTE;");
st.addBatch("TRUNCATE TABLE VIEW_CATEGORY_MASTER;\n");
st.addBatch("TRUNCATE TABLE VIEW_SUBCAT_MASTER;\n");
st.addBatch("TRUNCATE TABLE VIEW_VOD_MASTER;\n");

st.addBatch("TRUNCATE TABLE ASSETS_URL_DETAILS;\n");
st.addBatch("TRUNCATE TABLE SONY_LIV_IMAGE;\n");

st.addBatch("TRUNCATE TABLE VOD_METADATA_REMOTE;\n");

st.addBatch("TRUNCATE TABLE CLIENT_WEB_URL_REMOTE;\n");

System.out.println("SIZE:"+iList.size());
try{
//FileWriter fstream = new FileWriter("out.txt");
//BufferedWriter out = new BufferedWriter(fstream);


for(int i=0;i<iList.size();i++){
//System.out.println("--["+iList.get(i)+"]");
st.addBatch((String)iList.get(i));
//System.out.println(iList.get(i)+"\n");
//out.write((String)iList.get(i));
}
//Close the output stream
//out.close();
}catch(Exception ex){
ex.printStackTrace();
}

/*String tmpList=(String)iList.get(iList.size()-1);
String[] strs=tmpList.split(";");
System.out.println("Total:"+strs.length);
for(int j=0;j<strs.length;j++){
if(!strs[j].trim().equals("")){
st.addBatch(strs[j].trim()+";");
}
}*/


//st.addBatch("UPDATE version set CHHANNEL_VERSION=CHHANNEL_VERSION+1;");
        st.addBatch("UPDATE version set PKG_VERSION=PKG_VERSION+1;");
//st.addBatch("UPDATE version set VOD_VERSION=VOD_VERSION+1;");

  int [] counts=null;
 try{
 counts = st.executeBatch();
// counts =10;
 System.out.println("count"+counts.length);
 mySqlConn.commit();
 System.out.println("Catalog Sync Process has been done now updating version summary");

 }catch(Exception e){
 
e.printStackTrace();

 }
 if(counts!=null && counts.length>0){
 ResultSet rs=st.executeQuery("select max(ver_version) from version_summary where ver_type='CatalogSync'");
 String mVersion=null;
if(rs.next())
mVersion=rs.getString(1);

 rs.close();
 System.out.println("Recent version was ["+mVersion+"]");
 int ver=0;
 if(mVersion!=null){
 ver= Integer.parseInt(mVersion);
 }
 ver=ver+1;
 st.executeUpdate("insert into version_summary(ver_type,ver_version,ver_date) values ('CatalogSync','"+ver+"',now())");
  st.executeUpdate("UPDATE sync_info SET sync_status = 'c',last_sync_time= now()");
 
   System.out.println("=====CATALOGSYNC=====:SUCCESS");
 
 
  System.out.println("REname Tables start Time =======["+new java.util.Date()+"]=====");
 
  st.executeUpdate("rename table unified.VOD_METADATA_REMOTE to unified.VOD_METADATA_tmp");
st.executeUpdate("rename table unified.VOD_METADATA to unified.VOD_METADATA_REMOTE");
st.executeUpdate("rename table unified.VOD_METADATA_tmp to unified.VOD_METADATA");

st.executeUpdate("rename table unified.LANGUAGE_MASTER_REMOTE to unified.LANGUAGE_MASTER_tmp");
st.executeUpdate("rename table unified.LANGUAGE_MASTER to unified.LANGUAGE_MASTER_REMOTE");
st.executeUpdate("rename table unified.LANGUAGE_MASTER_tmp to unified.LANGUAGE_MASTER");

st.executeUpdate("rename table unified.PACKAGE_MASTER_VIEW_REMOTE to unified.PACKAGE_MASTER_VIEW_tmp");
st.executeUpdate("rename table unified.PACKAGE_MASTER_VIEW to unified.PACKAGE_MASTER_VIEW_REMOTE");
st.executeUpdate("rename table unified.PACKAGE_MASTER_VIEW_tmp to unified.PACKAGE_MASTER_VIEW");


st.executeUpdate("rename table unified.PACKAGE_CHANNEL_MAP_VIEW_REMOTE to unified.PACKAGE_CHANNEL_MAP_VIEW_tmp");
st.executeUpdate("rename table unified.PACKAGE_CHANNEL_MAP_VIEW to unified.PACKAGE_CHANNEL_MAP_VIEW_REMOTE");
st.executeUpdate("rename table unified.PACKAGE_CHANNEL_MAP_VIEW_tmp to unified.PACKAGE_CHANNEL_MAP_VIEW");

st.executeUpdate("rename table unified.CLIENT_WEB_URL_REMOTE to unified.CLIENT_WEB_URL_tmp");
st.executeUpdate("rename table unified.CLIENT_WEB_URL to unified.CLIENT_WEB_URL_REMOTE");
st.executeUpdate("rename table unified.CLIENT_WEB_URL_tmp to unified.CLIENT_WEB_URL");

st.executeUpdate("rename table unified.ASSETS_URL_DETAILS to unified.ASSETS_URL_DETAILS_tmp");
st.executeUpdate("rename table unified.CHANNEL_RTSP_DETAILS_VIEW to unified.ASSETS_URL_DETAILS");
st.executeUpdate("rename table unified.ASSETS_URL_DETAILS_tmp to unified.CHANNEL_RTSP_DETAILS_VIEW");

 System.out.println("REname Tables END Time =======["+new java.util.Date()+"]=====");


 }else{
System.out.println("CATALOGSYNC:FAILED");
 }
            }
        }
        catch( Exception e ) {
            System.err.println("Unable to connect to MySQL database: "+e);
           
        }finally{
  if(st!=null){
try{
st.close();
}catch(Exception e){
System.out.println("Exception occured while closing SQL Statement");
}
  }
}
    }

    /** Main method takes arguments for connection to JDBC etc. */
    public static void main(String[] args) {

        /*if (args.length != 1) {
            System.err.println("usage: db2sql <property file>");
        }*/
        // Right so there's one argument, we assume it's a property file
        // so lets open it
System.out.println("==========================================================================================================================");
        Properties props = new Properties();
        try {
    System.out.println("Catalog SYNC Started at:["+new java.util.Date()+"] sync variable ::: "+System.getenv("SYNC"));
            //props.load(new FileInputStream(args[0]));
            //props.load(new FileInputStream(new java.io.File("D:\\Vineetworks\\Dev\\Java\\MSSQL2sql.properties")));
            props.load(new FileInputStream(new java.io.File("/usr/syncservice/props/Oracle2sql.properties")));
System.out.println("properties loaded");
            //System.out.println(dumpDB(props));
   StringBuffer backupBuf=new StringBuffer();
            //backupBuf.insert(0, "TRUNCATE TABLE Program_Details;\n");
    backupBuf.append("TRUNCATE TABLE CHANNEL_MASTER_VIEW;\n");
backupBuf.append("TRUNCATE TABLE PACKAGE_MASTER_VIEW_REMOTE;\n");
backupBuf.append("TRUNCATE TABLE PACKAGE_CHANNEL_MAP_VIEW_REMOTE;\n");
backupBuf.append("TRUNCATE TABLE LANGUAGE_MASTER_REMOTE;\n");

backupBuf.append("TRUNCATE TABLE SONY_LIV_IMAGE;\n");
backupBuf.append("TRUNCATE TABLE VOD_METADATA_REMOTE;\n");
backupBuf.append("TRUNCATE TABLE CLIENT_WEB_URL_REMOTE;\n");
backupBuf.append("TRUNCATE TABLE ASSETS_URL_DETAILS;\n");



   System.out.println("Configuring ###########TEST########### Environment for Catalog SYNC :["+new java.util.Date()+"]");
   backupBuf.append(dumpDB(props));
 
//for(int i=0;i<insList.size();i++){
/* System.out.println("1 ["+insList.get(0)+"]");
System.out.println("2 ["+insList.get(1)+"]");
System.out.println("3 ["+insList.get(2)+"]");
System.out.println("4 ["+insList.get(3)+"]");
System.out.println("5 ["+insList.get(433)+"]");*/
//}

   backupBuf.append("UPDATE version set CHHANNEL_VERSION=CHHANNEL_VERSION+1;\n");
   backupBuf.append("UPDATE version set PKG_VERSION=PKG_VERSION+1;\n");
    //System.out.println("DUMP CREATED@@@@@"+backupBuf.toString());
//insList.size();
System.out.println("-----Inlist @@@@@"+insList.size());
batchInsert(insList);
insList.clear();
insList=null;
   /*FileOutputStream out=null;
   try{
   out=new FileOutputStream(new java.io.File("/usr/syncservice/dump/BackupCatalog.sql"));
           out.write(backupBuf.toString().getBytes());
            }catch(Exception e){
System.out.println("Exception occured while writing Catalog data to file stream"+e);
   }finally{
if(out!=null){
out.flush();
out.close();
}
   }

    System.out.println("Backup File has been generated Now need to dump to mysql database");
            execShellCmd();
            System.out.println("Completed at:["+new java.util.Date()+"]");
   */
System.out.println("Completed at:["+new java.util.Date()+"]");
        System.out.println("==========================================================================================================================");
} catch (IOException e) {
            System.err.println("Unable to open property file: "+args[0]+" exception: "+e);
        } catch (Exception ex) {
ex.printStackTrace();
}

    }
}

Thursday, 24 September 2015

Install mongo db in linux(REHL)

http://stackoverflow.com/questions/5726032/couldnt-connect-to-server-127-0-0-1-shell-mongo-js
yum install mongodb

2 down vote
I got the same problem when I tried to install mongo. I got Error as,
Error
"Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84"
Solution:
First install mongod by using:
sudo apt-get install mongodb-server
Then type
mongod --dbpath /mongo/db
Then
sudo rm /var/lib/mongodb/mongod.lock
Then
sudo -u mongodb mongod -f /etc/mongodb.conf  --repair
Thank You



up vote 79 down vote favorite
24
when i setup mongodb in my ubuntu , i try : ./mongo it show this error :
 couldn't connect to server 127.0.0.1 shell/mongo.js
so what can i do ,
thanks
https://www.gravatar.com/avatar/89f01563b72005c7cc016f49222acff3?s=32&d=identicon&r=PG

zed_0xff
15.2k43253
asked Apr 20 '11 at 5:45
https://www.gravatar.com/avatar/bdcbdae67b6057dd65cc301b4a5a1989?s=32&d=identicon&r=PG

zjm1126
6,7562879121
  
 
How did you install it? Did you use a aptitude? Did you download the tarbal directly? –  Bryan Migliorisi Apr 21 '11 at 0:58
  
 
i had this error and it was because on ubuntu I didn't run mongod first –  Connor Leech Apr 30 '14 at 8:16
add a comment
13 Answers
up vote 122 down vote
  • Manually remove the lockfile: sudo rm /var/lib/mongodb/mongod.lock
  • Run the repair script: sudo -u mongodb mongod -f /etc/mongodb.conf --repair
Please note the following:
  • You must run this command as the mongodb user. If you run it as root, then root will own files in /var/lib/mongodb/ that are necessary to run the mongodb daemon and therefore when the daemon trys to run later as the mongodb user, it won't have permissions to start. In that case you'll get this error: Unable to create / open lock file for lockfilepath: /var/lib/mongodb/mongod.lock errno:13 Permission denied, terminating.
  • On Ubuntu, you must specify the configuration file /etc/mongodb.conf using the -f flag. Otherwise it will look for the data files in the wrong place and you will see the following error: dbpath (/data/db/) does not exist, terminating.
https://i.stack.imgur.com/dJzQJ.png?s=32&g=1

mquandalle
2,1771020
answered Jul 27 '11 at 17:47
https://www.gravatar.com/avatar/3f1f8fa854d83b1f1b76ff55e1618d05?s=32&d=identicon&r=PG

fady mohamed osman
1,6371813
  
 
Great link. Solved the problem exactly. –  jaketrent Mar 14 '12 at 14:00
3
 
link seems broken. –  catphive Jul 11 '12 at 0:43
1
 
The answer is above now. –  fady mohamed osman Jul 11 '12 at 16:32
1
 
how to run that as the mongodb user? –  Jim Thio Aug 29 '12 at 3:49
2
 
I've had to use both the information of this answer and from @boulder_ruby 's answer. This because my '/data/db/' was missing. Maybe it could be a good update for this answer to be more complete. –  Fabricio Buzeto Jan 8 '13 at 18:57
up vote 26 down vote
sudo rm /var/lib/mongodb/mongod.lock  
sudo -u mongodb mongod -f /etc/mongodb.conf --repair
sudo service mongodb start
Here is all, sometimes, it take a little while to being started mongo after perform this operation.
answered Apr 17 '13 at 5:20
https://i.stack.imgur.com/E36nI.jpg?s=32&g=1

Rubyrider
1,8501118
1
 
thanks so much, that fixed it for me –  Sam Jun 17 '14 at 22:22
add a comment

up vote 19 down vote
Trying running $mongod
If you get en error such as
MongoDB shell version: 2.0.5
connecting to: test
Fri Jun  1 11:20:33 Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84
exception: connect failed

hisham-agil:~ hisham$ mongod
mongod --help for help and startup options
Fri Jun  1 11:24:47 [initandlisten] MongoDB starting : pid=53452 port=27017 dbpath=/data/db/ 64-bit host=hisham-agil.local
Fri Jun  1 11:24:47 [initandlisten] db version v2.0.5, pdfile version 4.5
Fri Jun  1 11:24:47 [initandlisten] git version: nogitversion
Fri Jun  1 11:24:47 [initandlisten] build info: Darwin gamma.local 11.3.0 Darwin Kernel Version 11.3.0: Thu Jan 12 18:48:32 PST 2012; root:xnu-1699.24.23~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_49
Fri Jun  1 11:24:47 [initandlisten] options: {}
Fri Jun  1 11:24:47 [initandlisten] exception in initAndListen: 10296 dbpath (/data/db/) does not exist, terminating
Fri Jun  1 11:24:47 dbexit:
Fri Jun  1 11:24:47 [initandlisten] shutdown: going to close listening sockets...
Fri Jun  1 11:24:47 [initandlisten] shutdown: going to flush diaglog...
Fri Jun  1 11:24:47 [initandlisten] shutdown: going to close sockets...
Fri Jun  1 11:24:47 [initandlisten] shutdown: waiting for fs preallocator...
Fri Jun  1 11:24:47 [initandlisten] shutdown: lock for final commit...
Fri Jun  1 11:24:47 [initandlisten] shutdown: final commit...
Fri Jun  1 11:24:47 [initandlisten] shutdown: closing all files...
Fri Jun  1 11:24:47 [initandlisten] closeAllFiles() finished
Fri Jun  1 11:24:47 dbexit: really exiting now
Then you've run into a basic startup error that is pretty common.
By default mongod will try to use /data/db for its database files, which in this case, does not exist.
You can't start
mongo
until you handle
mongod.
Try creating those directories and make sure they are writable by the same user that is running the mongod process.
answered Aug 8 '12 at 3:15
https://www.gravatar.com/avatar/7149d2bc15314277ac69357ef7251650?s=32&d=identicon&r=PG

boulder_ruby
12k43854
  
 
you can also set the dbpath like so: mongod --dbpath ../data –  cbaigorri Mar 26 '13 at 4:53
add a comment
up vote 18 down vote
This is actually not an error... What happens here is that Mongo relies on a daemon in order to run the local database server, so in order to "fire up" the mongo server in your shell, you have to start the mongo service first.
For Fedora Linux (wich is the Distro I use) You have to run these commands:
1 sudo service mongod start
2 mongo
And there you have it! the server is going to run. Now, If you want Mongo service to Start when the system boots then you have to run:
sudo chkconfig --levels 235 mongod on
And that's all! If you do that, now in the shell you just have to type mongo in order to start the server but that's pretty much it, the problem is you have to start the SERVICE first and then the SERVER :)
P.S. The commands I posted might work on other linux distros as well, not just in fedora... In case not maybe you have to tweak some words depending on the distro you're using ;)
answered Feb 2 '12 at 7:12
https://www.gravatar.com/avatar/78d99fe61b306155ed3e893ab5245795?s=32&d=identicon&r=PG

Jmlevick
1,50751629
  
 
Same Solution applies to question: stackoverflow.com/questions/7958228/… –  Jmlevick Feb 2 '12 at 7:13
  
 
So many times I get stumped and scratch my head for a long time, and finally realize: 'oh, I just have to sudo." –  ben author Aug 7 '12 at 2:57
2
 
and for Debian/Ubuntu variants: sudo service mongodb start –  Leon Stafford Oct 13 '12 at 22:45
add a comment

up vote 6 down vote
You need to delete the lockfile mongod.lock or /var/lib/mongodb/mongod.lock on ubuntu, then you need to run mongod.exe or service mongodb start on ubuntu first, then run mongo.exe or mongo on ubuntu.
https://www.gravatar.com/avatar/58f24aeb5a98725b985a0b5ff78c2052?s=32&d=identicon&r=PG

pylover
3,01421743
answered May 12 '12 at 15:36
https://www.gravatar.com/avatar/6a3181d7693baccabdc821a5bb8ebf7b?s=32&d=identicon&r=PG

  
 
The OP is on Ubuntu, so I'm pretty sure they won't be using any .exe files. –  me_and Jun 1 '12 at 16:27
  
 
I'm getting this error message, and I can't find a "mongod.lock" on my file system. Do these instructions apply to Mac OSX? –  boulder_ruby Aug 8 '12 at 3:00
add a comment
up vote 5 down vote
First start your mongo server by
Users-MacBook-Pro:csv1 Admin$ mongod
all output going to: /usr/local/var/log/mongodb/mongo.log
Then open another terminal window and open shell
Users-MacBook-Pro:csv1 Admin$ mongo
answered Nov 9 '13 at 6:38
https://www.gravatar.com/avatar/d2ef2cf60d9499a4e52d4d14b80fd8b7?s=32&d=identicon&r=PG

Tarun Gupta
2,55111524
  
 
thank you! short sweet and to the point. solved it for me. –  Dan Carlstedt Apr 3 '14 at 4:02
add a comment

up vote 5 down vote
Either your mongod is not running (check using "ps" command) or it is listening on some outside IP address and not on localhost. So first check the process list if 'mongod' is running. If yes, check with "netstat -nap" for the related port.
Of course you can start mongod on the console manually or even look into the mongod logfile (if there is one configured...depending on how you installed mongod).
answered Apr 20 '11 at 6:29

add a comment
up vote 4 down vote
First you have to make sure that all the files and directories in your /var/lib/mongodb/ folder (or whichever folder dbpath points to) belong to the mongodb user and mongodb group.
cd /var/lib/mongodb/
sudo chown mongodb filename.*
sudo chgrp mongodb filename.*
sudo chown -R mongodb directory
sudo chgrp -R mongodb directory
(Replace filename and directory with their respective names)
Then you can remove the lock, repair the database and restart the daemon as other people already mentioned:
sudo rm /var/lib/mongodb/mongod.lock  
sudo -u mongodb mongod -f /etc/mongodb.conf --repair
sudo service mongodb start
answered May 13 '13 at 19:46
https://www.gravatar.com/avatar/c1061441a24b13b6fd486cda07e1041d?s=32&d=identicon&r=PG

Vulcanor
1064
  
 
How come there are no upvotes to this? This was the only solution, among half a dozen SO entries that I looked, that worked for me. Thank you, sir. –  FRD Dec 22 '13 at 16:11
  
 
The command to start with the config file and force a repair is sudo -u mongodb mongod -f /etc/mongod.conf --repair on Ubuntu 14. –  okoboko Jun 15 '14 at 14:49
add a comment

up vote 2 down vote
I got the same problem when I tried to install mongo. I got Error as,
Error
"Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84"
Solution:
First install mongod by using:
sudo apt-get install mongodb-server
Then type
mongod --dbpath /mongo/db
Then
sudo rm /var/lib/mongodb/mongod.lock
Then
sudo -u mongodb mongod -f /etc/mongodb.conf  --repair
Thank You
https://www.gravatar.com/avatar/77dc3a788aa91829e0855babe561ff2a?s=32&d=identicon&r=PG

gran33
3,25611434
answered Jul 31 '14 at 8:58
https://www.gravatar.com/avatar/0b95b7578ef579415ed217a0a49f5528?s=32&d=identicon&r=PG

  
 
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. –  Ravimallya Jul 31 '14 at 9:21
  
 
If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. –  pzin Jul 31 '14 at 9:31
  
 
Will this method delete the existing databases in mongo? –  Evan Sep 15 at 15:19
add a comment
up vote 2 down vote
Also check that your root partition has enough space to start mongod.
df -h /
You'll see smth like this on mongod launch:
Mon Aug 12 17:02:59.159 [initandlisten] recover : no journal files present, no recovery needed
Mon Aug 12 17:02:59.159 [initandlisten]
Mon Aug 12 17:02:59.159 [initandlisten] ERROR: Insufficient free space for journal files
Mon Aug 12 17:02:59.159 [initandlisten] Please make at least 3379MB available in /var/lib/mongodb/journal or use --smallfiles
Mon Aug 12 17:02:59.159 [initandlisten]
Mon Aug 12 17:02:59.159 [initandlisten] exception in initAndListen: 15926 Insufficient free space for journals, terminating
Mon Aug 12 17:02:59.159 dbexit:
Mon Aug 12 17:02:59.159 [initandlisten] shutdown: going to close listening sockets...
answered Sep 22 '13 at 18:20
https://www.gravatar.com/avatar/6b673035165d7bd76a048d1c55a5f7f9?s=32&d=identicon&r=PG

DmitrySandalov
8941015
add a comment

up vote 1 down vote
On Ubuntu, try this:
sudo invoke-rc.d mongodb start
answered May 2 '13 at 13:04
https://www.gravatar.com/avatar/e762682299d402b3cc46c9d47b2a0a3a?s=32&d=identicon&r=PG

Victor
291
  
 
Only this solution worked for me out of all answers! Great. –  trex May 27 at 3:04
add a comment
up vote 1 down vote
It could be combination of $PATH and Permission issue.
Try following steps given below:
Update your $PATH variable to point to your MongoDB bin file. In my case brew install MongoDB to this folder:
/usr/local/Cellar/mongodb/2.4.6/
In order to update your $PATH variable, do following:
$ sudo vi /etc/paths
Then, press ‘i’ to insert text in Vi and append the your MongoDB path to the end of the ‘paths’ file and restart the terminal.
/usr/local/Cellar/mongodb/2.4.6/bin
Use ‘Esc : w q’ to save and exit from Vi editor.
Use echo to display your path variable:
$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/Cellar/mongodb/2.4.6/bin
Now try to check the Mongo version, if you get following, then you are on the right track!
$ mongo --version
MongoDB shell version: 2.4.6
Now we need to create the database directory. I used the default ‘/data/db’ location suggested in MongoDB docs. I also created a log directory to avoid any permission issues while Mongo tries to create any logs. Change ownership and that will do the job.
$ sudo mkdir /data/db
$ sudo mkdir /data/log
$ whoami
username
$ chown -R username /data
Now, we will create a default config file for MongoDB to be provided for the first time we run ‘mongod’ command. Now, I will also like to point out that ‘mongod’ will start a service, which will listen for incoming data connections. This is similar having ‘$service mysqld start’ executed.Let’s go ahead and create the config file. Please keep in mind that I have created very basic config file. However, you can add many other variables to configure MongoDB. This is the first time I am playing with MongoDB, so I just know as much as I read on MongoDB docs!I created ‘mongodb.conf’.
$ sudo vi /etc/mongodb.conf
Add following:
fork = true
port = 27017
quiet = true
dbpath = /data/db
logpath = /data/log/mongod.log
logappend = true
journal = true
Please note that the default port for MongoDB server is 27017. Use your own path for dbpath and logpath you created in Step – 5. Don’t forget to close and save the conf file.
Now we are all set to start our MongoDB service. Open two instances of Terminal.In Terminal 1, type in:
$ sudo mongod -f /etc/mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 3516
all output going to: /data/log/mongod.log
child process started successfully, parent exiting
If you get above message, then know that you have successfully started your Mongod service.
Now, to connect to it, in Terminal 2 type following:
$mongo test
MongoDB shell version: 2.4.6
connecting to: test
Server has startup warnings:
Tue Sep 3 16:55:43.527 [initandlisten]
Tue Sep 3 16:55:43.527 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
> 
Ignore the warnings, but you are successfully connected to the ‘test’ database! Cool!
That's all. I applied this solution, when I tried to install copy of MongoDB on my Mac for the first time. See if this help you too.
I hope it helps!
Cheers, Chinmay
answered Feb 9 '14 at 5:36
https://www.gravatar.com/avatar/43c5af2fcba82da75f68473d0bfdd433?s=32&d=identicon&r=PG&f=1

Chinmay
113
  
 
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. –  Radim Köhler Feb 9 '14 at 6:09
  
 
@RadimKöhler, thanks for heads up. I have corrected the answer. Hope this will help someone. Cheers. –  Chinmay Feb 9 '14 at 6:46
add a comment

up vote 1 down vote
I solved this problem on ubuntu 12.04 by following steps:
1) sudo rm /var/log/mongodb
2) sudo rm /var/lib/mongodb
3) I removed mongo and then installed it again
4) sudo service mongodb restart
and All is Well