I'm trying to connect to an Oracle database using JDBC Driver and I'm handle with an error: "java.sql.SQLException: Invalid Oracle URL specified".
My code is the following:
import java.sql.*;
public class L9
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin;#localhost:1521:xe","user","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from table");
while(rs.next())
System.out.println(rs.getInt(1) + " "+rs.getString(2)+ " "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Anyone knows what is the problem?
It should be
jdbc:oracle:thin:#localhost:1521:xe
instead of
jdbc:oracle:thin;#localhost:1521:xe
(note the : after the "thin")
It is better to use a long format connection URL where you have the ability to pass connection descriptors. Easy Connection URL (jdbc:oracle:thin:#//localhost:1521/myorcldbservicename) ) does establish the connection but does not provide any High Availability capabilities.
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=myhost)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=myorcldbservicename)))
Related
So I'm trying to connect my java code to mysql and when I run the code below nothing prints out not even the error. I'm following a YouTube tutorial and understand everything except where he is getting "jdbc:mysql:" from. Any help would be awesome thanks.
package ztestconnection;
import java.sql.*;
public class Test {
static String Username = "Klongrich";
static String Password = "********";
static String Connection = "jdbc:mysql://localhost:8080/hospital";
public static void main(String [] args){
Connection con = null;
try{
con = DriverManager.getConnection(Connection, Username, Password);
System.out.println("Connected");
} catch(Exception e){
System.out.println(e);
}
}
To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.
1:- Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Before you can open a connection, you need to load the specific driver class, like so:
try
{
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception ex)
{
// handle the error
}
This ensures that java.sql.DriverManager can find the driver class definition.
There's some good example code in the MySQL Connector/J documentation.
As for the jdbc:mysql: part of the DSN (Data Source Name), that's a standard syntax that tells the driver manager and the database that they're opening a JDBC connection to a MySQL database. It will be explained in the Oracle Java documentation.
And Tim has a good point about your variable names. Don't give a variable the same name as a class. Even if it doesn't confuse the compiler, it'll confuse the hell out of the maintenance programmer (you) about a week from now.
I want to access to NexusDB V3 with Java.
So I have a Java project with many files that connects to the database. Can anyone tell me if it is possible to use a Java class file for connecting to the database.
I've tried JDBC connector and the ODBC connector but nothing is working.
I have read about a bridge between them but I don't know how to make it so please help.
public class dbConnect {
public static void connect(){
Connection conn;
Statement stmt;
ResultSet rs;
String sql;
conn = null;
String url = "jdbc:mysql://localhost:3306/db_oopproject";
try{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,"user","12345");
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
sql = "Select * from user_account";
rs = stmt.executeQuery(sql);
}
catch (Exception e){
System.out.print(e.getMessage());
}
}
}
first off, your url contains "mysql", are you sure that will work for the jdbc bridge to connect to NexusDB?
I don't know why i am getting this error infact i write code write and also add java connector in my project.
Please any one resolve my issue
import java.sql.*;
public class jbdcdemo {
public static void main(String[] args) {
try{
//1. Get Connection to DB
Connection myConn = DriverManager.getConnection("jbdc:msql://localhost:3306/world","root","1234");
//2. Create a statement
Statement myStmt = myConn.createStatement();
//3. Execute sql query
ResultSet myRs = myStmt.executeQuery("SELECT * FROM world.city;");
//4. Process the results
while(myRs.next()){
System.out.println(myRs.getString("Name")+", "+myRs.getString("District"));
}
}
catch(Exception exc){
exc.printStackTrace();
}
}
}
Try fixing the connection string:
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/world","root","1234")
Looks like you have semicolon for the sql statement,
Below is the correct one.
ResultSet myRs = myStmt.executeQuery("SELECT * FROM world.city");
i am using my following code in eclipse using derby database,but getting the error as
Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:322)
at java.sql.DriverManager.getConnection(DriverManager.java:273)
at jdbc.JDBCSample.main(JDBCSample.java:19)."
package jdbc;
import java.sql.*;
public class JDBCSample {
public static void main( String args[]) {
String connectionURL = "jdbc:derby://127.0.0.1:8080/SAMPLE";
// Change the connection string according to your db, ip, username and password
try {
// Load the Driver class.
Class.forName("org.apache.derby.jdbc.ClientDriver");
// If you are using any other database then load the right driver here.
//Create the connection using the static getConnection method
Connection con = DriverManager.getConnection (connectionURL);
//Create a Statement class to execute the SQL statement
Statement stmt = con.createStatement();
//Execute the SQL statement and get the results in a Resultset
ResultSet rs = stmt.executeQuery("select moviename, releasedate from movies");
// Iterate through the ResultSet, displaying two values
// for each row using the getString method
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate"));
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
}
}
}
I think your problem will be solved, if you
call getConnection("..", "..", "..") method with username and password.
Example
Connection con = DriverManager.getConnection(connectionURL, "sa", "sa");
Hi Below is the code I wrote for connecting to Oracle DB using JDBC connection and return some values. But this code establish the connection and returns the result if I am opening the oracle toad in my machine.
But when the oracle toad is closed and try to run this code, it will not connect.
Please let me knwo how to connect to oracle DB with out opening the oracle toad manually.
package library;
import java.io.IOException;
import java.sql.*;
public class DBAutomationConnection {
public static void main(String args[]) throws ClassNotFoundException, IOException, SQLException {
DBAutomationConnection dbconn = new DBAutomationConnection();
//Connection conn = dbconn.DBConnection1();
dbconn.DBConnection1("select * from employee where empid='test123'","ROLE_NAME");
}
public void DBConnection1(String query, String colName)throws IOException, ClassNotFoundException{
Connection connection = null;
Statement stmt = null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:oracle:thin:#//testhostname:1528/ServiceName", "XXAAA_U", "Jw9S");
System.out.println("Connection successful: " +connection);
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//String UserID = rs.getString("USER_ID");
String UserID = rs.getString(colName);
System.out.println(UserID);
}
} catch (SQLException e ) {
System.out.println("Could not execute query.");
//JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
} catch (SQLException e) {
System.out.println("Could not connect to the database");
}
}
You should initialize Oracle TNS-Listener Service from your OS settings>services. You may need to check your tns configuration.
you need to install ORACLE client in your system to connect oracle remotely.
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
Do you have Oracle Thin driver installed in your system? This link can guide you.