I am trying to connect to Oracle DB hosted by the faculty.
Given information:
host: bazi.finki.ukim.mk
port: 1521
sid: ORCL
user: xxx
pass: xxx
here is the code:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection c = DriverManager.getConnection("jdbc:oracle:thin:#bazi.finki.ukim.mk:1521:ORCL","user","pass");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
I get "IO Error: The Network Adapter could not establish the connection"
Also i want to mention that, every group (by the way, this is for project) have workspace... also protected with username and password, even if I can connect into the database, how can i connect to the workspace?
...And also, they wrote that there need to be created tunnel with Putty, is that necessary and how to create it?
This is from http://www.orafaq.com/wiki/JDBC
There are 2 URL syntax, old syntax which will only work with SID and the new one with Oracle service name.
Old syntax
jdbc:oracle:thin:#[HOST][:PORT]:SID
New syntax
jdbc:oracle:thin:#//[HOST][:PORT]/SERVICE
Also note that these 2 lines are unnecessary
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
DriverManager will automatically detect the necessary driver by url, see API
Related
I am creating an application where you can manage an mySql database, at first i want the user to connect to the host by suppling the hostname, username and password. here is my code:
try {
Class.forName(ServerConnect.JDBC_DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Cannot register JDBC Driver...");
}
try {
conn = DriverManager.getConnection("jdbc:mysql://"
+ toServer.getHostname() + "/hrmanagement?" + "user=" + toServer.getUsername()
+ "&password=" + toServer.getPassword());
System.out.println("Connected to the server!");
} catch (SQLException e) {
System.out
.println("Not Connected to the server. Make sure username or password is correct!");
}
my question is, how can i connect without specifying the database so that i can let my user choose which database can he connect to. i tried removing "/hrmanagement?" but it didn't connect to the server. what can i do?
From the documentation:
The JDBC URL format for MySQL Connector/J is as follows, with items in square brackets ([, ]) being optional:
jdbc:mysql://[host][,failoverhost...][:port]/[database] ยป
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
So, remove hrmanagement, note that the / and ?user... parts are staying
my question is, how can i connect without specifying the database so
that i can let my user choose which database can he connect to. i
tried removing "/hrmanagement?" but it didn't connect to the server.
what can i do?
Move the question mark to "?user=". I think the other answer had this correct.
In terms of changing databases, I believe you can use setCatalog() to use a different database.
From the Connection Page:
void setCatalog(String catalog)
throws SQLException
Sets the given catalog name in order to select a subspace of this
Connection object's database in which to work.
If the driver does not support catalogs, it will silently ignore this
request.
Calling setCatalog has no effect on previously created or prepared
Statement objects. It is implementation defined whether a DBMS prepare
operation takes place immediately when the Connection method
prepareStatement or prepareCall is invoked. For maximum portability,
setCatalog should be called before a Statement is created or prepared.
Parameters:
catalog - the name of a catalog (subspace in this Connection object's database) in which to work Throws:
SQLException - if a database access error occurs or this method is called on a closed connection See Also:
getCatalog()
It would probably be easier to use this version of the call, a little less confusing
public static Connection getConnection(String url,
String user,
String password)
throws SQLException
So your code would look like
try {
conn = DriverManager.getConnection("jdbc:mysql://" + toServer.getHostname(),
toServer.getUsername(),
toServer.getPassword());
conn.setCatalog("someDifferentDB");
System.out.println("Connected to the server!");
} catch (SQLException e) {
System.out.println(e.toString());
}
As a side note, getConnection will attempt to load the JDBC driver for you, so you don't really need to whole Class.forName try/catch block. That's a vestige of old code that's not needed for most of the modern JDBC drivers. There's still some around that need it, but I believe mysql conforms to the newer style. Just make sure the driver is in your classpath on the command line
java -cp \path\to\mysql\driver\driver.jar myProgram
I'm trying to connect to my database using sqljdbc4, I'm pretty new to this so i followed a couple of tutorial but it still doesn't seem to work, When i try to run the program i get this Exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''. ClientConnectionId:f181fd37-7e28-4392-ac86-02914c2090e1
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
And this is my code:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
You are not passing any authentication credentials. If you want to use integrated security (windows authentication), then you need to explicitly specify that in your connection URL and you need to load the native library required for this.
See Connecting with Integrated Authentication On Windows on Windows on MSDN.
This essentially comes down to including the folder containing the (32 bit or 64 bit) sqljdbc_auth.dll in the java.library.path system property (see link for details) and adding integratedSecurity=true to your connection string:
DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=DBank;integratedSecurity=true");
You are passing empty username and password while connecting to the database in getConnection method:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
Try supplying the db username and password, for example:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","myusername","mypassword");
I'm a java beginner and I'm working on a simple application which connects to a remote mysql database using JDBC. I've tested it locally and it works just fine, however I cannot get it to work on for my remote server.
I don't think its of much use but heres the code:
Connection connection = null;
String dburl = "jdbc:mysql://314159265:3306/Db_Name";
String userName = "user";
String passWord = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dburl, userName, passWord);
Statement st = connection.createStatement();
String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
int rsI = st.executeUpdate(query);
System.out.println("Hi");
}catch (Exception e) {
System.out.println(e);
} finally {
if (connection != null) {
try {
connection.close();
System.out.println("Database connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
When I run this, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.The driver has not received any packets from the server.
I'm pretty sure it must be some kind of server configuration issue.
Notes:
Username, password, IP, database name, etc. are just examples.
This could be a firewall problem, or a configuration problem. But I don't think it is a coding problem at all - you need to start troubleshooting the connection.
Trouble shoot by attempting to use third party client apps to connect to mysql. This will indicate whether it is configured for external access. Although it doesn't ensure that JDBC is visible from the outside, it does rule out some potential firewall problems.
Follow this guide to help you mess with your configurations
Remote MYSQL Database Access
If you are still stuck, it could be a coding problem so check out this page:
How to connent to a remote mysql database with java?
P.S. I am assuming you are using unix as the operating system.
I guess 314159265 could be replaced by some address....
like jdbc:mysql://localhost:3306/
or jdbc:mysql://127.0.0.1:3306/
I have a Solid Database. And I want to connect to this DB by JDBC. How can I get URL for connection creation?
[EDIT]
For more information:
SOLID JDBC Driver
Programmer's Guide
SOLID JDBC Driver 2.3 Readme
Registering JDBC Driver
The JDBC driver manager, which is written entirely in Java, handles loading and unloading drivers and interfacing connection requests with the appropriate driver. It was JavaSoft's intention to make the use of a specific JDBC driver as transparent as possible to the programmer and user.
The driver can be registered with the three alternative ways, which are shown below. The parameter required by Class.forName and Properties.put functions is the name of the driver, which is solid.jdbc.SolidDriver.
// registration using Class.forName service
Driver)Class.forName("solid.jdbc.SolidDriver")
// a workaround to a bug in some JDK1.1 implementations
Driver d = (Driver)Class.forName("solid.jdbc.SolidDriver").newInstance();
// Registration using system properties variable also
Properties p = System.getProperties();
p.put("jdbc.drivers", "solid.jdbc.SolidDriver");
System.setProperties(p);
Connecting to the database
Once the driver is succesfully registered with the driver manager a connection is established by creating a Java Connection object with the following code. The parameter required by the DriverManager.getConnection function is the JDBC connection string.
Connection conn = null;
try {
conn = DriverManager.getConnection(sCon);
}
catch (Exception e) {
System.out.println("Connect failed : " + e.getMessage());
throw new Exception("Halted.");
}
The connect string structure is jdbc:solid://://. The string "jdbc:solid://fb9:1314/dba/dba" attempts to connect a SOLID Server in machine fb9 listening tcp/ip protocol at port 1314.
The application can establish several Connection objects to database. Connections can be closed be the following code.
conn.close();
I ve installed MySQL (last update).
I need to code, that ll create & establish a connection with SQL DB
& manage the DB(using SELECT, INSERT, CREATE).
I did everything but, I am not able to create connection. I've also installed the MySQL/J connector, I just extracted the .zip pack in a folder & added the folder path in Variables).
Can anyone tell me wat is meant by URL in the below line?
Connection connection = DriverManager.getConnection(url, username, password);
I ve tried this:
String url = "jdbc:odbc:sqlserver://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
But it's not working. I am unable able to understand the term 'URL'.
Can anyone explain, the meaning of 'url' and wat should be done to connect to a SQL server from Java.
Update:
This is the Full code. It still cannot connect.
import java.sql.*;
public class TestDriver {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//This s wat actually i did for connection
System.out.println("Driver Loaded Succesfully");
}
catch (Exception e){
System.out.println("Unable to Load Driver!!!");
}
try {
Class.forName(com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
System.out.println("connection Established");
}
catch(Exception e) {
System.out.println("Couldnt get connection");
}
}
}
Can you tell me wat is the purpose of MySQL Connector/J?
In the question you seem to be using a MySQL jdbc driver with a SQL Server jdbc URL. This won't work.
If you are using a MySQL database:
Class.forName("com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
If you are using a SQL Server database you are going to need a completely different jdbc driver. jTDS is open source and a good option. Include the jtds.jar file in your classpath and use something like:
Class.forName("net.sourceforge.jtds.jdbc.Driver"); // initialise the driver
String url = "jdbc:jtds:sqlserver://localhost:1433/myfirstdb";
Here's an extract from your code:
} catch (Exception e) {
System.out.println("Couldnt get connection");
}
You should never suppress exceptions as long as you don't understand its cause. Replace it by at least:
} catch (Exception e) {
System.out.println("Could not get connection");
e.printStackTrace();
}
Or maybe
} catch (Exception e) {
throw new RuntimeException("Could not get connection", e);
}
Either way, you should see the exception type, message and trace. In your code snippet the possible exceptions are ClassNotFoundException and SQLException. The first one would mean that the driver is not properly placed in the classpath. The second one would mean that connection cannot be obtained. The exception message and/or trace should tell in detail about the underlying root cause of the problem.
You should always observe exceptions. They tell something about the cause of the problem. You know, once a cause is understood, the solution is nothing more than obvious :)
See also:
Short MySQL/JDBC tutorial - Contains explanation about exception causes.
Further,
Can anyone tell me wat is meant by URL in the below line?
An URL is an Uniform Resource Locator. It's a common way to locate (identify) unique resources in computer systems and networks. The URL syntax for the MySQL database is explained in the documentation of the JDBC driver.
Can you tell me wat is the purpose of MySQL Connector/J?
It's the JDBC driver. The JDBC API exist of almost only interfaces. The DB vendors should provide their own concrete JDBC API implementation, which is the JDBC driver. With a JDBC driver you'll be able to connect a specific database using JDBC API.
If its MS SQL Server,
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
For more info, see this to get started with Microsoft JDBC.
You can use any of the two JDBC drivers for MSSQL:
Microsoft SQL Server JDBC Driver
2.0
jTDS
For MS SQL Server driver 2.0, use
URL: jdbc:sqlserver://server:port; DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
For MySql & Java, see this on SO.
You forgot a " at Class.forName(com.mysql.jdbc.Driver");
It should be
Class.forName("com.mysql.jdbc.Driver");