Guys,
I know there are some new features in JDBC4.0 and one of them is that you don't need to load database drivers explicitly as the JDBC API will automatically load the driver when you call getConnection(). So I just wanna test it.
BTW, I use Eclipse as my Dev Tool.
Here are my code snippets:
public class Test002JDBCRowSet {
public static void main(String[] args) throws Exception{
String connURL = "jdbc:oracle:thin:#192.168.1.150:1521:";
String database = "bmdw";
String userName = "bmdw";
String passWd = "bmdw";
String driver = "oracle.jdbc.driver.OracleDriver";
String SQLStr = "select t.Empno, t.Ename, t.job, t.sal from employer t where t.sal > 1500";
/*
try{
Class.forName(driver);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
*/
//Latest Method4 : Search for some data with RowSet, offline!
RowSetFactory rsf = RowSetProvider.newFactory();
try(
Connection conn = DriverManager.getConnection(connURL + database,userName,passWd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLStr);
CachedRowSet cachedRS = rsf.createCachedRowSet();){
cachedRS.populate(rs);
conn.close();
System.out.println("======Employee List -- Salary more than 1500======");
System.out.printf("%-15s%-15s%-15s%-15s%n","Employee No.","Employee Name","Employee Job","Employee Salary");
try{
while(rs.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
while(cachedRS.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
I got the runtime exception :
java.sql.SQLException: No suitable driver found for
jdbc:oracle:thin:#192.168.1.150:1521:bmdw
However, if I remove the comments about loading oracle driver explicitly, it works well.
And I'm sure I have already add the ojdbc14.jar into classpath.
So I don't know what happened. I'm trying to figure out how does the method 'getConnection()' works.
I checked System.getProperties() but there is no property named 'jdbc.driver'. Even if I added it and set the value to 'oracle.jdbc.driver.OracleDriver'. It still doesn't work.
I checked ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName()) and I found there is only one default file :
jar:file:/D:/Java/jdk1.7.0_03/jre/lib/resources.jar!/META-INF/services/java.sql.Driver
I has so far achieved little.
There might be some oversight in the configuration of Eclipse.
Hope anyone can help me.
Thanks.
I agree with #kordirko and his comment. OP also seems to have confirmed that his problem is resolved because of his comment. Hopefully he gets notification of this and makes it an answer. :)
Check this link: http://docs.oracle.com/cd/E11882_01/java.112/e16548/jdbcvers.htm#JJDBC28109 --> You need to have the ojdbc6.jar in your classpath environment variable in order to have JDBC 4.0 standard support. – kordirko
Related
I try to create a connection between JDBC and MS Access.
I follow the instruction as per this link. I am using IntelliJ Idea. Here I am sharing some snaps to describe my problem.
This is the code that I write down to make a connection with Database Database2. But as you can see there is no error neither any output. Now I am sharing the table structure and content on the table.
2nd picture is
My code is:
import java.sql.*;
public class Connection_sample {
public static void main(String[] args) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn= DriverManager.getConnection("jdbc:ucanaccess://D://tutorial/Database2.accdb");
Statement s = conn.createStatement();
s.executeQuery("select * from Student");
ResultSet rset = s.getResultSet();
while (rset.next()) {
System.out.println(rset.getInt(1)+""+rset.getInt(2));
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Can anyone help me to find the error?
Your problem is the result of using getResultSet() instead of using the result set returned by executeQuery(). You should only use getResultSet() in combination with execute().
A result set should only be obtained once, and it was already returned from executeQuery (which you ignored). When you called getResultSet, you - apparently - got an empty one (which technically violates the contract).
I have been starting off with some JDBC a few days ago as of 2019/3. And there was this error occurring when I try to comply the code below in my eclipse IDE.
I actually did some research before this and I have tried:-
-Adding external libraries from the project menu
-Reinstalling and trying out different ides(thinking it was just eclipse but turns out its something about my system)
-reinstalled both jdk and the jdbc connector
and still, the problem persists.
import java.sql.*;
public class Driver{
public static void main(String[]args)throws Exception {
String url = "jdbc:mysql://localhost:3306/main";
String uName = "Ng Jun Han";
String pW = "password";
String query = "SELECT first FROM students WHERE id = 1";
Class.forName("com.sql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uName, pW);
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
rs.next();
String name = rs.getString("first");
System.out.print(name);
st.close();
con.close();
}
}
This is how my project directory looks like
My biggest concern regarding the topic is about something wrong I did with the installation methods. Mainly because there are not much up-to-date resources to follow.If so, does anyone know the CORRECT way of fixing it?(the driver jar file is located at C:\Program Files\MySQL , and i c/p-ed it into my the libraries file in my project directory) Thanks for helping:)
Try this class name :
Class.forName("com.mysql.cj.jdbc.Driver")
Refer to the official docs
How can get the name of the database name from connection object
try {
this.ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/amger");
} catch (NamingException ne) {
}
Connection conObj = ds.getConnection();
How do I get that Database name from con
Probably the most straightforward way to get the database name from the JDBC Connection object itself is via the getCatalog() method:
Connection#getCatalog()
However, as Konstantin pointed out in his comment below, that value will not change if the current MySQL database is changed by issuing a USE dbname statement.
getCatalog() might still be useful in an application that
does not change databases, or
does things "The JDBC Way" by using setCatalog() to change the current database,
but for MySQL, using SELECT DATABASE() appears to be safer overall.
Note also that this potential discrepancy between getCatalog() and the actual current database depends on the behaviour of the particular JDBC driver. Out of curiosity I tried something similar with the Microsoft JDBC Driver 4.0 for SQL Server and .getCatalog() was indeed aware of the change to the current database immediately after running a USE dbname statement. That is, the code
String connectionUrl = "jdbc:sqlserver://localhost:52865;"
+ "databaseName=myDb;" + "integratedSecurity=true";
try (Connection con = DriverManager.getConnection(connectionUrl)) {
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
try (Statement s = con.createStatement()) {
System.out.println(" Executing: USE master");
s.execute("USE master");
}
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
} catch (Exception e) {
e.printStackTrace(System.out);
}
produced the following results:
getCatalog() returns: myDb
Executing: USE master
getCatalog() returns: master
If you know that DB is Mysql you could just perform SELECT DATABASE() on your connection and read the resulset with current database name in it.
Here is description of DATABASE function.
Let's assume you used url as "jdbc:mysql://localhost/test"
Then do the following:
DatabaseMetaData dmd = connection.getMetaData();
String url = dmd.getURL();
System.out.println(url.substring(url.lastIndexOf("/") + 1));
Run
System.out.println(connection.getMetaData().getURL());
Paste the output in notepad
search the value for 'databaseName=yourDBName'
So a little background on my problem: I am trying to copy over a table on an Microsoft SQL system from an Oracle database. Besides giving password and user access to the table I cannot edit or do anything to the MSSQL database.
I successfully used the Oracle SQL Developer to connect and view the tables I want (using a third party JDBC driver), but I want to set up an automated copy-over into my Oracle database so I am attempting to use the same driver in some stored java code.
I have a java function that all it should do is go and count the number of entries in the table. So far my code looks like:
public static String getCount() {
Statement stmt = null;
Connection conn = null;
int rowCount = 0;
String message = "";
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println("Error loading driver: " + e);
message = message + e + " -ER1 \n";
}
try {
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://site.school.edu:2000/ACCESS", "user", "password");
stmt = conn.createStatement();
String strSelect = "select 1 as field;";
ResultSet rset = stmt.executeQuery(strSelect);
while (rset.next()) {
++rowCount;
}
}
catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + " -ER2";
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + "-ER3";
}
}
return message;
}
Which is being calling from a stored function :
CREATE OR REPLACE function Schema.java_testMessage return varchar2
as language java
name 'ConnectAndQuery.getCount() return java.lang.String';
Which I am calling from a script in TOAD:
set serveroutput on;
declare
words varchar2(400);
begin
words := KSL_ADMIN.java_testMessage;
dbms_output.put_line(words);
end;
However the result is that I'm getting:
java.lang.ClassNotFoundException: net/sourceforge/jtds/jdbc/Driver -ER1
08001 -ER2
PL/SQL procedure successfully completed.
I have the jar file within the class path, I can't think of any reason it shouldn't have the nessecary permissions to see the jar, and as far as I can tell I have everything spelled correctly.
Please help me figure out what I am doing wrong. Or if there is perhaps an easier way to go about connecting an Oracle DB to an MSSQL DB without really installing anything. Any knowledge on this is welcome as I am pretty new to a lot of this.
Oracle has its own internal java virtual machine and it does not use the system classpath. If you need external libraries you must “load” them into the internal JVM. You can do this using Oracle's loadjava tool.
See the Oracle's loadjava documentation (http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheleven.htm#JJDEV10060)
Is there a standard way to connect a Java program to a MySQL database, and which is the easiest one?
JDBC is the standard way also the easiest.
In addition to answer posted above, JPA (Hibernate) is even easier one once you cross the initial barrier called learning curve (and before you are hit by next one called, Performance Optimization). On the serious note, Yes JPA is also a standard way to connect and query pretty much any database the same way.
JDBC is the standard way. Below is the sample java code to connect MySQL database:
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String db = "testdb";
String dbUser = "root";
String dbPasswd = "mysql123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "DELETE FROM user WHERE email = 'riponalwasim#gmail.com'";
int delete = st.executeUpdate(sql);
if(delete >= 1){
System.out.println("Row is deleted.");
}
else{
System.out.println("Row is not deleted.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
Maybe object-relational mapping with Hibernate is a useful way for you.