I have added multiple jars(ojdbc6 for oracle and jtds-1.2.jar for sqlserver ) to my classpath.
When I test connection using following code :
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
if(conn==null){
System.out.println("false");
}
else{
System.out.println("true");
}
Scenario 1:
If I give JDBC_DRIVER as sqlserver URL (net.sourceforge.jtds.jdbc.Driver)
and DB_URL,USER,PASS for my oracle instance then also it will create connection for me but logically it is wrong.
Scenario 2:
If I give some other(not oracle.jdbc.driver.OracleDriver ) valid class in ojdbc6.jar and valid DB_URL,USER,PASS then also it will create connection .
But I always want to check valid JDBC_DRIVER which corresponds to the given DB_URL,USER,PASS
I have also tried registerDriver and deregisterDriver API available in driverManager. What are the pros and cons of using it.
Explanation for - Scenario 1/Scenario 2
From oracle documentation
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
So even you comment out Class.forName(JDBC_DRIVER); you will get the same result as ojdbc6 is in your classpath and in DriverManager.getConnection(...); method you are passing oracle database related information.So DriverManager always will return the connection instance for oracle daabase only.
Explanation for- want to check valid JDBC_DRIVER which corresponds to the given DB_URL,USER,PASS
For this you can use getDriver(String url) method of DriverManager class.
getDriver(String url)
Attempts to locate a driver that understands the given URL.
To check valid driver name try these lines below.
conn = DriverManager.getConnection(this.dbUrl, this.dbUser, this.dbPassword);
DatabaseMetaData dbMetaData = conn.getMetaData();
this.databaseProperties.add("Driver Name: " + dbMetaData.getDriverName());
Related
I’m trying to connect a Java program to a remote Oracle DB. After doing some research online, I decided that the easiest way to do this was with the Oracle JDBC driver. I downloaded and ran the jar file and got the message “***** JCE UNLIMITED STRENGTH IS INSTALLED *****.” The problem is that when I try to add the driver to my classpath (javac -classpath ojdbc8.jar Connect.java), I keep getting an error message saying “package oracle.jdbc.driver does not exist.” I’ve been researching how to fix this online, but I’m only getting confused. Any ideas on what I did wrong?
import java.sql.*;
public class Class1 {
public static void main (String args [])
throws SQLException
{
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// Connect to the database
// You must put a database name after the # sign in the connection URL.
// You can use either the fully specified SQL*net syntax or a short cut
// syntax as `<host>`:`<port>`:`<sid>`. The example uses the short cut syntax.
Connection conn =
DriverManager.getConnection ("jdbc:oracle:thin:hr/hr#myhostname:1521:orcl",
"myUsername", "myPassword");
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ENAME from EMP");
// Iterate through the result and print the employee names
while (rset.next ())
System.out.println (rset.getString (1));
conn.close(); // ** IMPORTANT : Close connections when done **
}
}
The error is:
java: package oracle.jdbc.driver does not exist
Can you try to run the sample DataSourceSample.java? Make sure you have the JDBC driver in the classpath. You can also refer to this quickstart for detailed instructions.
So I've been able to connect to MySQL through Netbeans on my older computer, using the following code:
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza?user=root";
Connection con = DriverManager.getConnection(connectionUrl,"root","root");
However, since getting a new computer, every time I try to run the code, it comes up with this error:
SQL Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
database 'root'
Being fairly new to coding in general, I tried researching different queries online but couldn't come up with a solution.
Notes:
-I tried changing different sections of my code, making sure I didn't miss any upper case/lower case letters
-I went onto MYSQL and ran a command to check all the database names, and made sure to copy the right one down
-No matter how I change the code in anyway, it always says "unknown database 'root'" even though I haven't put root down as the database name
Any help would be greatly appreciated!
Your database URL should not have the ?user=root suffix.
Make it look like so, as you are specifying the username/password already in the getConnection(url, username, password) call.
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
Since it is asking from username and password in next step while making con object you should not specify it in connection url.
Try to run code by removing the ?user=root from your connection url.
String connectionUrl = "jdbc:mysql://localhost:3306/tblpizza";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tblpizza","root","root");
Try this way, you can omit the connectionUrl variable.
I have used JDBC to connect to many different relational systems over the years: H2, HSQLDB, MySQL, Oracle, Postgres, etc. And in every case, each system seems to have its own flavor of connection string syntax.
I can't imagine that a long-standing API like JDBC wouldn't have a defined, enforced grammar for connection string validation. For example:
Some valid HSQLDB connection strings:
jdbc:hsqldb:mem:mymemdb
jdbc:hsqldb:res:org.my.path.resdb
jdbc:hsqldb:file:/opt/db/testdb
MySQL:
jdbc:mysql://localhost/test
Postgres:
jdbc:postgresql://localhost/test
H2:
jdbc:h2:~/test
jdbc:h2:file:/data/sample
jdbc:h2:tcp://dbserv:8084/~/sample
From all these examples, I gather the basic, generalized syntax:
jdbc:<vendor>:<vendor-specific-uri>
Where <vendor> is the name of the system (h2, mysql, etc.), and <vendor-specific-uri> is either a path or some vendor-specific way of determining the location of a database.
I've done a lot of digging, and for the life of me, I can't seem to find where JDBC defines valid connection string syntax. Specifically:
What is the general grammar/definition of a valid JDBC connection string?
What are the different names of each token/component of the connection string? For instance, is "jdbc:" called something, like the "JDBC protocol"? What is the proper name for my <vendor> and <vendor-specific-uri> segments?
The URL syntax is specified in the JDBC specification, specifically in section 9.4:
The format of a JDBC URL is :
jdbc:<subprotocol>:<subname>
where subprotocol defines the kind of database connectivity mechanism that may be supported by one or more drivers. The contents and syntax of the subname will depend on the
subprotocol.
Note – A JDBC URL is not required to fully adhere to the URI syntax as defined in RFC 3986, Uniform Resource Identifier (URI): Generic Syntax
There is no more formality to it than this. The subprotocol usually is some identifier for the database or the driver. Subname is freeform, although drivers usually do follow URI-like syntax.
There is also no need for more formality. The DriverManager will simply offer the URL to each registered java.sql.Driver in turn and the first one to accept is used to connect.
If you take a look into the source code, you will see that a JDBC driver implements java.sql.Driver. This interface has a method
boolean acceptsURL(String url) throws SQLException;
From the JavaDoc:
Retrieves whether the driver thinks that it can open a connection to the given URL. Typically drivers will return true if they understand the subprotocolspecified in the URL and false if they do not.
So the dirver for your database is responsible to implement this method. For H2, this implementation is
#Override
public boolean acceptsURL(String url) {
if (url != null) {
if (url.startsWith(Constants.START_URL)) {
return true;
} else if (url.equals(DEFAULT_URL)) {
return DEFAULT_CONNECTION.get() != null;
}
}
return false;
}
Other DBMS have different implementations.
Edit: For H2, the constant Constants.START_URL is "jdbc:h2:". So even the leading jdbc is not part of any formal grammar.
I have a Jbutton (GetDataFromDB) in a simple java application that is suppose to load the data from the database depicted in the path in the code below into a Jtable in the application.
Edited answer into code:
private void GetDataFromDBActionPerformed(java.awt.event.ActionEvent evt) {
Connection con;
ResultSet rs = null;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={MS Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
stmt = con.createStatement();
String query = null;
query = "select * from cost";
rs = stmt.executeQuery(query);
i = 0;
while (rs.next()){
i = i + 1;
jTable.getModel().setValueAt(rs.getString(1), i, 1);
jTable.getModel().setValueAt(rs.getString(2), i, 2);
}
rs.close();
stmt.close();
con.close();
} catch(Exception err){
System.out.println(err.getMessage());
}
}
When I press the button I get the following message in the run output window:
No suitable driver found for jdbc:odbc:Driver={Microsoft Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I have at the top of my code the import:
import java.sql.*;
I have also tried changing from "Microsoft Access Driver" to "MS Access Driver" but I get the same message in the run output window i.e.
No suitable driver found for jdbc:odbc:Driver={MS Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I'm really thankful for all your help, input and feedback.
Depending on the driver and If you are pre JDK 6**!
You need to register the driver.
Try adding:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
So:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
It's also worth mentioning you don't need to do this every time you get a connection, just once to make sure the class is loaded.
There are a lot of stackoverflow questions relating to this, but the reason for it is below:
Source - From The Java Tutorial:
In previous versions of JDBC, to obtain a connection, you first had to
initialize your JDBC driver by calling the method Class.forName. This
methods required an object of type java.sql.Driver. Each JDBC driver
contains one or more classes that implements the interface
java.sql.Driver. ... Any JDBC 4.0 drivers that are found in your class
path are automatically loaded. (However, you must manually load any
drivers prior to JDBC 4.0 with the method Class.forName.)
On a related and very important note.
I would also recommend looking up how to handle connections. External Resources like database connections and cursors are easy to leak if you are not familiar with them. Look up 'try finally blocks', or more recently in java 7+ 'try-with-resources'.
I'm trying to get insert ID while after inserting some data in my database.
String sql = "INSERT INTO ADI.DUMMY(dummy_data) VALUES('from database logger')";
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int extUptReturn = ps.executeUpdate(sql);
But I got this exception:
Java exception: ''java.lang.UnsupportedOperationException'';
thrown from class name: ''sun.jdbc.odbc.JdbcOdbcConnection'', method name: ''prepareStatement'', file: ''JdbcOdbcConnection.java'', line: '1762'
The ODBC bridge driver doesn't support it. Nothing to do against. Either replace the driver or live with it. I would just use a real JDBC driver instead of the poorly-developed, feature-lacking, bug-rich Sun ODBC bridge driver. Almost all self-respected server based RDBMS vendors provides a fullworthy JDBC driver for download at their homepage. Just Google "[vendorname] jdbc driver download" to find it. Here's an overview:
MySQL JDBC driver
PostgreSQL JDBC driver (note: older versions didn't support generated keys as well).
Oracle JDBC driver (note: older versions didn't support generated keys as well).
MSSQL JDBC driver (or performancewise better, the jTDS JDBC driver)
DB2 JDBC driver is hard to find in IBM's online forest, but it's usually already included in the /java folder of the DB2 installation.
UCanAccess driver for Microsoft Access databases (more details here).
MAy be the JDBC implementation could not be supporting the sepcific opration.
CHeck the JDBC driver used.
Try this example instead of Statement.RETURN_GENERATED_KEYS:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection
.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
Where BRANCHID is the auto generated id