Oracle java connection - java

I have written a connection code with oracle. But still I am getting errors. I'll type the code of mine here.
import java.sql.*;
public class SimpleOraJava {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
String serverName="10.20.228.67";
String user="root";
String password="root";
String SID="abc";
String URL="jdbc:oracle:thin:#"+serverName+":"+1520+":"+SID;
Connection conn=DriverManager.getConnection(URL, user, password);
String SQL="Select employeename from employee";
Statement stat=conn.createStatement();
ResultSet rs=stat.executeQuery(SQL);
while (rs.next()){
System.out.println(rs.getInt(1));
}
stat.close();
conn.close();
}
}
It shows error in this line:
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The error is on the word Oracle. It is asking me to create class in package oracle.jdbc.driver
Please somebody help!

Okay, assuming that class-paths are set up, and the appropriate .jar files are in the correct directories, the first thing that jumps out is I believe you need to import the package into your class. There should be a import oracle.jdbc.driver.*; line under the import java.sql.*; line also the DriverManager call should be
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
with the lowercase o, it's capitalized in your code.
Another thing might be, the version of the Oracle JDBC, and Oracle client you're using. According to this OTN Discussion post Oracle JDBC 10.2 is the last release to support the package oracle.jdbc.driver.
So basically according to the metalink page if you're using a JDBC 10.2 or older client, something like this will work:
import java.sql.*;
import oracle.jdbc.driver.*;
public class myjdbcapp
{
public static void main(String[] args) throws SQLException
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
String url = "jdbc:oracle:thin:#server:port:orcl";
String userName = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection (url, userName, password);
OracleCallableStatement myprocst = (OracleCallableStatement)
conn.prepareCall ("begin myproc(?); end;");
// ...
}
}
Clients newer than JDBC 10.2 will need to change import oracle.jdbc.driver.; to import oracle.jdbc.;

DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The package is oracle.jdbc.driver with a lowercase o.

Related

How Interface can refer to object where no interface is implemented?

I created a connection to a mysql database. Below is my code
package org;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DatabaseConn {
public static void main(String[] args) {
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
try {
String host = "jdbc:mysql://localhost:3306/sys";
String username = "root";
String password = "root";
Connection Con = DriverManager.getConnection(host, username, password);
Statement stmnt = Con.createStatement();
String SQL = "SELECT * FROM sys_config";
ResultSet rs = stmnt.executeQuery( SQL );
System.out.println("Records:"+rs);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
}
My Understanding towards Interface implementation on classes says, Interface type reference to an object of class that implements Interface.
But when I investigated below code snippet used in above code..
Connection Con = DriverManager.getConnection(host, username, password);
DriverManager.getConnection(host, username, password) returns a reference(of type Connection) to a object but no interface is implemented in class DriverManager. Can anyone clear my this doubt ..? Or I missed out anything ?
Same thing am not able to get with below code snippet
Statement SQL = Con.createStatement();
Con.createStatement() should return a reference to a object that implements Statement interface. But this Connection interface is implemented by ConnectionImpl class where implementation is present like below
public class ConnectionImpl
extends ConnectionPropertiesImpl
implements Connection {
public Statement createStatement()
throws SQLException
{
return createStatement(1003, 1007);
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException
{
checkClosed();
StatementImpl stmt = new StatementImpl(this, this.database);
stmt.setResultSetType(resultSetType);
stmt.setResultSetConcurrency(resultSetConcurrency);
return stmt;
}
}
Let's look at this bit by bit:
DriverManager.getConnection(host, username, password) returns a reference (of type Connection) to a object...
This is correct.
...but no interface is implemented in class DriverManager.
This is also correct.
What your explanation is missing is that DriverManager.getConnection() doesn't return a reference to the DriverManager. It returns a reference to an object of a different class, one that does implement the Connection interface.
Let's say for the sake of argument that there is a class called MySqlConnection:
class MySqlConnection implements Connection {
...
}
Now, DriverManager.getConnection() could well return an instance of this class:
class DriverManager {
public Connection getConnection(...) {
return new MySqlConnection(...);
}
}
Hope this clears things up.
getConnection and createStatement are factory methods. Note that the interface is implemented in the returning object class.
Only the interfaces like DriverManager, Connection , Statement etc. are declared in the JDK , the concrete classes which implement them are there in the corresponding JDBC driver you use. For ex., in your case it is mysql jdbc driver added in your class path. So, it is these concrete implementations in the driver jar that knows how to connect to the Database and talk to it. JDK has just defined the specification in the form of interfaces that all the vendor classes should implement. This makes the java code independent of any change in the Database and the corresponding driver.

JDBC connectivity issue

My code for connection with access database is this...its working fine here... i have tried to connect my database with java derby embedded database but always getting sql exception assuming the same table what changes do i need to connect my application with java derby embedded database??
package database;
import java.sql.*;
import javax.swing.JOptionPane;
public class database {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String url = "jdbc:odbc:personnew";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection(url);
Statement st=con.createStatement();
String sql="SELECT * FROM Person";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
String id=rs.getString("id");
String name=rs.getString("name");
String fathername=rs.getString("fathername");
JOptionPane.showMessageDialog(null,id+"\t"+name+"\t"+fathername);
}
// TODO code application logic here
}catch(Exception sqlEx){
System.out.println("Sql exception");
}
}
}
For one thing, You would need to use the correct JDBC driver; org.apache.derby.jdbc.EmbeddedDriver
http://db.apache.org/derby/papers/DerbyTut/embedded_intro.html
The tutorial in general is probably where you want to start as it tells you everything you need to know:
http://db.apache.org/derby/papers/DerbyTut/index.html

Cannot connect jdbc to sql server

Below is my code for a simple select query for the Sql Server using jdbc.
import java.sql.*;
import java.util.*;
public class DateServer{
public void dbconnect(String conn, String user, String pass){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(conn, user, pass);
System.out.println("connected");
Statement stat = con.createStatement();
String query = "select * from headcount_new";
ResultSet rs = stat.executeQuery(query);
}
catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
DateServer conserver = new DateServer();
conserver.dbconnect("jdbc:sqlserver://<<hostname>&gt", "<<username>&gt", "<<password>&gt");
}
}
I am getting the following error:
com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.Util.parseUrl(Util.java:420)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.parseAndMergeProperties(SQLServerDriver.java:856)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:838)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at DateServer.dbconnect(DateServer.java:9)
at DateServer.main(DateServer.java:22)"
Can someone please help me what the error is about? I am new to Java.
thanks.
Not sure why you have <<hostname>&gt etc
A JDBC URL looks like this
jdbc:sqlserver://SomeServer;user=SomeUser;password=XXX;
this has nothing to do with java. in your connection string you have to replace '<hostname>', '<username>', etc. with actual values. See here for valid syntax: http://www.java2s.com/Tutorial/Java/0340__Database/AListofJDBCDriversconnectionstringdrivername.htm

Error in My java oracle connectivity ... java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I just got some errors in my Java oracle connectivity. Could anyone please help me with this? I have enclosed the code below. I'm getting this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver..
this is the code
package md5IntegrityCheck;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class MD5IntegrityCheck
{
public static void main(String[] args)
{
String fileName,Md5checksum ,sql;
Connection con;
PreparedStatement pst;
Statement stmt;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 =DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
}
catch(Exception ee)
{ee.printStackTrace( );}
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/****insert method******/
private static void setDefaultCloseOperation(String exitOnClose) {
// TODO Auto-generated method stub
}
static void setVisible(boolean b) {
// TODO Auto-generated method stub
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
PreparedStatement pst = con.prepareStatement("insert into RecordTbl values(?,?)");
String fileName = null;
pst.setString(1,fileName);
String Md5checksum = null;
pst.setString(2,Md5checksum);
int i=pst.executeUpdate( );
System.out.println("recorded in database");
con.close( );
}
catch(Exception ee)
{ee.printStackTrace( );}
}
}
if (args.length <= 0)
{
Md5Gui gui = new Md5Gui();
gui.runGui();
}
else
{
DoWork runningProgram = new DoWork();
runningProgram.run(args);
}
}
}
Your question is vague:
In your exception, you're getting a ClassNotFoundException for a driver that pertains to MySQL. On your code, you're using a JDBC-ODBC Driver.
My suggestion is how did you configure your database connectivity. Let's start from there. Also, it would be better to add the exception stack trace to see exactly what's happening.
Edit: Visit this example if you want to know how to configure JDBC connection to Oracle Database. I fully recommend using the Oracle JDBC driver directly instead of connecting it to an ODBC Bridge.
I assume you might be running your program in IDE, so please add drivers jars in the classpath of project
You should look into any 3rd party library you're using whether there a MySQL database driver is needed. Although you write you are using an Oracle driver (though the JdbcOdbcDriver is provided by Java itself and has nothing to do with Oracle DB's) the exception is clearly stating that the MySQL is requested. Since you don't use it in the code you provided, there must be another database connection using MySQL.

How do I connect to a SQL Server 2008 database using JDBC?

I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.
jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms
username="shuxer" password="itarator"
There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:
String userName = "username";
String password = "password";
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
after adding sqljdbc4.jar to the build path.
For Window authentication you can do something like:
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).
Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!
You can use this :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from sysobjects where type='u'";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
"<password>");
}
}
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName
I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress
Do not forget check if SQL Server Browser service is running.
You can try configure SQL server:
Step 1: Open SQL server 20xx Configuration Manager
Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
Step 3: Click tab IP Address, Edit All TCP. Port is 1433
NOTE: ALL TCP port is 1433
Finally, restart the server.
Simple Java Program which connects to the SQL Server.
NOTE: You need to add sqljdbc.jar into the build path
// localhost : local computer acts as a server
// 1433 : SQL default port number
// username : sa
// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conn {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Connection conn=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");
if(conn!=null)
System.out.println("Database Successfully connected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLUtil {
public void dbConnect(String db_connect_string,String db_userid,
String db_password) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from cpl";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} }
public static void main(String[] args) {
SQLUtil connServer = new SQLUtil();
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB",
"sa",
"0123");
}
}
Try this
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
String url ="Jdbc:jtds:sqlsever://ip/instanceName;instance=instanceName;databseName=dbName;user=yourUser;password=yourpass;";

Categories

Resources