简体   繁体   中英

Connecting to database with JDBC URL

My requirement is to check can we connect to a database with no schema defined through a java program and create a database. this works fine

Connection  connection =
           DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/db2inst1","vmadmin","password@123;");

database: db2 schema: db2inst1

but

Connection  connection =
           DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/","vmadmin","password@123;");

fails WHY?

com.ibm.db2.jcc.am.mo: [jcc][10165][10045][4.7.85] Invalid database URL syntax: jdbc:db2://wcspocca-db.cloudapp.net:50001/. ERRORCODE=-4461, SQLSTATE=42815
DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/!!DBNAME!!","vmadmin","password@123;");

Because in the second example the database is not specified. You can find the requirements in the DB2 JDBC documentation :

>>-+-jdbc:db2:------+--//--server--+---------+--/--database----->
   +-jdbc:db2j:net:-+              '-:--port-'
   '-jdbc:ids:------'

>--+---------------------------+-------------------------------\><
   '-:--| connection-options |-'

The database parameter is not optional.

How I usually connect to a database using jave is like the following: Spacing it out to allow you to read the text below

//Wide Scope Variables
static Connection conn = null; //right now this connection is off
static String dbURL = "database url"; //I use SQL developer and your able to grab the connection url there

static String user = "This can be empty and ask user for input of hard code the user name";

static String pass = "same as above";

In the method where you want to check the driver and connection I usually do it like this

//Register the Driver
    try
    {
        Class.forName("oracle.jdbc.driver.OracleDriver");   
    }
    catch(ClassNotFoundException e)
    {
        System.err.println(e.getMessage());
    }

    //Set up connection
    try
    {
        conn = DriverManager.getConnection(dbURL,user,password);
        conn.clearWarnings();
        stmt = conn.createStatement();
    }
    catch(SQLException e)
    {
        System.err.println(e.getMessage());
    }

The first try catch code registers the driver to the SQL developer then the second try catch sets up the connection to the database. This helped save me a lot of head aches and I find it the most Direct route when using java.

check the url carefully, after the port number if you do not put database name which you want to connect then how it will connect. Its like you are giving a home address whitout the plot number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM