java derby Error connecting to server localhost 1527 - java

I want to connect derby DB to Java application. I have downloaded all the jars, set a classpath as a java directory and downloaded Derby.What I get now is:
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Can anyone help me:what does it actually mean, and what can I do now?I guess there might be a problem with Database_url variable, but I don't know how to set it propely.
private static final String protocol = "jdbc:derby:";
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Loaded the client driver.");
} catch (Exception err) {
System.err.println("Unable to load the client driver.");
err.printStackTrace(System.err);
System.exit(0);
}
String dbName = "BookDatabase";
Connection conn = null;
try {
System.out.println(
"Connecting to and creating the database...");
conn = DriverManager.getConnection(DATABASE_URL);
System.out.println("Database created.");
Statement s = (Statement) conn.createStatement();
s.execute("CREATE TABLE names" +
"(author varchar(50), author_id " +
"int, url varchar(80))");
System.out.println("Created 'names' table.");
System.out.println("Inserting authors.");
s.execute("INSERT INTO names " +
"VALUES ('Adams, Douglas', 1," +
"'http://www.douglasadams.com')");
s.execute("INSERT INTO names " +
"VALUES ('Simmons, Dan', 2, 'http://www.dansimmons.com')");
s.execute("INSERT INTO names " +
"VALUES ('Stephenson, Neal', 3, " +
"'http://www.nealstephenson.com')");
System.out.println("Authors inserted.");
conn.close();
} catch (SQLException err) {
System.err.println("SQL error.");
err.printStackTrace(System.err);
System.exit(0);
}
}

Given your error (Connection refused: connect) it seems that the database server has not been started. Apache Derby has two operation modes: client/server and embedded. Each mode uses different drivers (and have different JDBC URL syntax).
The ClientDriver is used for client/server mode (which works as a traditional RDMS), so you need to start the Derby DB Server as a different Java process:
java -cp derby.jar;derbynet.jar;derbyclient.jar;derbytools.jar org.apache.derby.drda.NetworkServerControl start
(and java ... NetworkServerControl stop in order to shutdown the database process).
Another alternative is starting the DB in embedded mode (the database and the client both run in the same JVM, but no other process can connect to the database at the same time).
The embedded mode uses org.apache.derby.jdbc.EmbeddedDriver and the datasource URL has the form jdbc:derby:firstdb;create=true.
See this example, which is explained in Activity 3: Run a JDBC program using the embedded driver of the Getting Started with Derby guide.
Note that in embedded mode, some additional steps must be executed in order to properly shutdown the database before exiting the JVM.

Related

Connecting to remote HIVE server

I am trying to connect to a remote hive server. I have the following maven java code :
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
// Register driver and create driver instance
Class.forName(driverName);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ForHive.class.getName()).log(Level.SEVERE, null, ex);
}
// get connection
System.out.println("before trying to connect");
Connection con = DriverManager.getConnection("jdbc:hive://<hostip>:10000/", "hive", "");
System.out.println("connected");
// create statement
Statement stmt = con.createStatement();
// execute statement
stmt.executeQuery("CREATE TABLE IF NOT EXISTS "
+" consultant ( eid int, name String, "
+" salary String, destignation String)"
+" COMMENT ‘Employee details’"
+" ROW FORMAT DELIMITED"
+" FIELDS TERMINATED BY ‘\t’"
+" LINES TERMINATED BY ‘\n’"
+" STORED AS TEXTFILE;");
System.out.println("Table employee created.");
con.close();
}
But when I execute it gets stuck while trying to connect to the server and throws no exception either.
Try to use org.apache.hive.jdbc.HiveDriver driver.
Connection string
jdbc:hive2://<host>:10000/
Following ways are reasons for your problem.
1.Hive JDBC Class path is "org.apache.hive.jdbc.HiveDriver" and not "org.apache.hadoop.hive.jdbc.HiveDriver".
2.For hive server,
You can able to use like below.
Connection con = DriverManager.getConnection("jdbc:hive://:10000/default", "", "");
3.If you have using hiveserver2,
you have use below connection.
Connection con = DriverManager.getConnection("jdbc:hive2://:10000/default", "", "");
Above ways are surely helpful to you

Connection to Oracle Database with Java

I can't connect to my Oracle database server. This is the code :
import java.util.*;
import java.sql.*;
import java.io.IOException;
public class Knigi {
public static void main(String[] args) {
String baza_DRIVER="oracle.jdbc.driver.OracleDriver";
String baza_STRING="jdbc:oracle:thin:#localhost:1521:";
String baza_USERNAME="knigi";
String baza_PASSWORD="knigi";
Locale.setDefault(Locale.ENGLISH); // Vazhno e bidejkji Oracle treba da znae kakvi poraki da pojavuva
try {
Driver Driver = (Driver)Class.forName(baza_DRIVER).newInstance();
Connection Conn = DriverManager.getConnection(baza_STRING,baza_USERNAME,baza_PASSWORD);
PreparedStatement Statement = Conn.prepareStatement("SELECT * FROM zhanrovi");
ResultSet zhanrovi = Statement.executeQuery();
boolean isEmpty = !zhanrovi.next();
boolean hasData = !isEmpty;
while (hasData) {
System.out.println("Zhanr: "+zhanrovi.getString("ZH_IME"));
PreparedStatement Statement2 =
Conn.prepareStatement("select * from knigi where ZH_BR = ?");
Statement2.setInt(1,zhanrovi.getInt("ZH_BR"));
ResultSet knigi = Statement2.executeQuery();
boolean isEmpty2 = !knigi.next();
boolean hasData2 = !isEmpty2;
if (isEmpty2) {
System.out.println(" - nema knigi");
} else {
System.out.println(" - Knigi:");
};
while (hasData2) {
System.out.println(
" " +
knigi.getString("ISBN") +
" - " +
knigi.getString("NASLOV")+" ");
hasData2=knigi.next();
}
knigi.close();
hasData=zhanrovi.next();
}
zhanrovi.close();
Conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
And I am getting this message:
java.sql.SQLException: Io exception: Connection refused(DESCRIPTION=(TMP=)(VSNNUM=186646784)(ERR=12504)(ERROR_STACK=(ERROR=(CODE=12504)(EMFI=4))(ERROR=(CODE=12504)(EMFI=4))))
In school, this example works. Where is the problem??
Try this, might help
jdbc:oracle:thin://<host>:<port>/<SERVICE_NAME>
service_name=SID of the database, most often ORCL.
cheers,
Do you have your DB server running at your local machine at: localhost:1521?
Your school machine might have DB server running on it but your home machine simply doesn't.
The db connection URL "jdbc:oracle:thin:#localhost:1521:" is normally not hard coded. Point it to localhost almost always fail it when you run your code on a different machine.
There are three major instances when you get such Connection refused error
There is no database server running at the host:port you have specified i.e at localhost:1521
Password you have entered is wrong.
The port you have specified is blocked by a firewall or you are behind some proxy that does not allow you to connect to that port.
You can manually try to connect to your database from command line and see if the connection is live.
Question has been closed ... I had to do a tunneling because my Faculty server has closed connection from out side the faculty network, also they told me that the password had been changed ....
btw tnx for the answers they helped me to connect to my local server and access my local data base ..
Thanks again mates ^_^

Unable to connect to MS Access Database

This is my code:
public class ConnectDB {
Connection conn;
Scanner kb=new Scanner(System.in);
public String ID;
public ConnectDB()
{
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("Driver successfully loaded");
}
catch (ClassNotFoundException c)
{
System.out.println ("Unable to load database driver");
}
//connect to the database
try
{
String filename = "PATPhase2DB.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=";
database += filename.trim () + ";DriverID=22;READONLY=true}";
conn = DriverManager.getConnection (database,"","");
System.out.println ("Connection to database successfully established");
}
catch (Exception e)
{
System.out.println ("Unable to connect to the database");
}
}
The Messages Are:
Driver successfully loaded
Unable to connect to the database
java.lang.NullPointerException
This has worked on a different computer than mine, connecting to the database through exactly the same code. I am also running Windows 8.
This is very common error.
Reason is that some other application is using your database (most commonly you have opened database in Microsoft Access).
Close it and enjoy.
EDIT:This answer is for error user mentioned in comment(unable to open registry key 'temporary (volatile))
add this to your code:
System.out.println ("Unable to connect to the database");
System.out.println ("Exception: " + e.getMessage());
then you can get a deeper glimpse of what went wrong
Your Driver= name is missing a space. You've defined it as...
Driver={Microsoft Access Driver (*.mdb,*.accdb)};
...but it should be...
Driver={Microsoft Access Driver (*.mdb, *.accdb)};
You also have a stray } at the end of your connection string, but that doesn't seem to hurt anything.
In this case you need to mention the entire path of your access database file and the url between extensions (.mdb, *.accdb) space is mandatory e.g.:
String database="C:/Users/GIRI/Desktop/fdsfkdsfj/abc.accdb";
String url="jdbc:odbc:Driver={Microsoft Access Driver (.mdb, *.accdb)};DBQ=" + database + ";DriverID=22;READONLY=true";

Access mysql data base from another system using java

I am working on a interface in java swing.we have four system connected with a lan.the interface is for accessing the database from the other system in the same local area network i used the following code to access the database by giving the ip address,database name,tablename but i could not connect the other systems database.how can i do this?
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Use below code
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
Class.forName("com.mysql.jdbc.Driver").newInstance ();
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
System.out.println("Name:" + rs.getString(1));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Also, make sure to include jar file for connecting. You will get jar file here.
Update 1:
So, you have a
CommunicationsException: Communications link failure
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Update 2
If your system is Windows, go to Start>>Run.
Type command. This will open command prompt.
Type "ping 192.168.1.61"
You might get reply in below format.
Pinging 192.168.1.61 [192.168.1.61] with 32 bytes of data:
Reply from 192.168.1.61: bytes=32 time=101ms TTL=124
If you don't get something in above format, then your MYSQL Server with ip 192.168.1.61 is NOT REACHABLE. Ask your team to start the server first. :(
If you have Linux version, open terminal and follow step 3.
Also check below link. Those might help you...
http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html
You should down load the jdbc driver and replace
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
by
Class.forName("com.mysql.jdbc.Driver");
If you still have issues asfter replacing Obdc stuff, please post the exception.
ALso check firewall settings and DB permissions.
If you'll get exception your app will not free system resources. This will work better:
} finally {
try {
rs.close();
st.close();
con.close();
} catch( Exception e ) {
e.printStackTrace();
}
}

JDBC MYSQL Connection without specifying database?

I am using the SphinxQL MySQL client which stores indexes as "tables" but has no real notion of a "database"...One specifies the port (9306 in my case) at which the sphinx mysql instance listens and in theory should be able to communicate as normal.
I have the following test code:
import java.sql.*;
public class Dbtest {
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:9306",
"user","password");
con.setReadOnly(true);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * from index_turned_table");
while (res.next()) {
String stuff1 = res.getString(1);
String stuff2 = res.getString(2);
System.out.println("Adding " + stuff1);
System.out.println("Adding " + stuff2);
}
res.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println (e);
}
}
Upon execution, the code just hangs and does nothing and doesn't print out an exception. What are useful things I can do to figure this out or if any one has direct experience what might be going on?
This work with 1.10-beta http://www.olegsmith.com/2010/12/scalalift-sphinxql.html
and not work with 2.0.1-beta. Use mysql-connector-java 5.1.15.
Your SphinxQL instance is listening on port 9306. Your MySQL is listening on some other port, likely on the default 3306. You can use MySQL JDBC driver to connect to MySQL, but you cannot use it to connect to SphinxQL. It just doesn't understand JDBC driver communication protocol.

Categories