cannot load JDBC Driver - java

I'm trying to understand JDBC API and in order to do so,I'm just writing some code to estabilish a connection to the DB. It seems that I can't...
I'm trying to manually load the Driver for mysql DB,but even if I include the connector .jar in the classpath the compiler complains that it can't find the package com.mysql.
If,on the other hand,I omit the Class.forName() method, the code compiles but I get a hundreds Exception lines at runtime.
I'm compiling (and running) including the jar in the command line:
javac -cp [path to jar] DBTest.java
here's my code:
import java.sql.*;
class DBTest {
**strong text**
static final String ADDRESS="jdbc:mysql://127.0.0.1:8888/customer";
static final String USER="myuser";
static final String PASSWORD="luca";
public static void main(String[] args) {
Connection conn=null;
Statement stat=null;
Class.forName("com.mysql.jdbc.Driver");
try {
conn=DriverManager.getConnection(ADDRESS,USER,PASSWORD);
stat=conn.createStatement();
String query="SELECT * FROM person";
ResultSet result=stat.executeQuery(query);
while (result.next()) {
String name=result.getString("name");
String surname=result.getString("surname");
int id=result.getInt("id");
String telephone=result.getString("telephone");
System.out.println(id+": first name: "+name+" second name: "+surname+" tel: "+telephone);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
conn.close();
stat.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Edit:
with the double quotes it now compiles fine, but at runtime it says something like:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Replace
Class.forName(com.mysql.jdbc.Driver);
with
Class.forName("com.mysql.jdbc.Driver");

Related

What is the best way Loading XML data to mySql using Java?

I am already working on a project to optimize interactions with dataBases using JAVA.
First Step , I began with loading XML data to mysql.
I found many articles working on this issue , and they parse Data before inserting it , like this article :
https://dzone.com/articles/load-xml-into-mysql-using-java
But I tried to do things simpler : so
I write this code that load data using LOAD local XML infile .. ( an sql Query ) and it works well .
package my.project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class App {
static final String dbUrl = "jdbc:mysql://localhost/dbOptimization";
static final String password = "azerty";
static final String user = "root";
public Connection conn;
/*
* Load jdbc Driver
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Dirver loaded");
} catch (ClassNotFoundException ex) {
System.err.println("Cannot load driver " + ex);
}
}
/*
* Connect to DB
*/
public void connect() {
try {
conn = DriverManager.getConnection(dbUrl, user, password);
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Cannot connect the database!");
}
}
/*
* Create Table and Load Data
*/
public void createTable() {
try {
conn.createStatement().execute("create Table badges(Id INTEGER,UserId VARCHAR(20),Name varchar(20),Date DATE ,Class INTEGER ,TagBased VARCHAR(20))");
System.out.println("table created");
conn.createStatement().execute("Load xml local infile '/home/lenovo/Bureau/Project/3dprinting/Badges.xml'into Table badges(Id,UserId,Name,Date,Class,TagBased)");
System.out.println("data parsed");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("connot create Table" + e);
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
App app =new App();
app.connect();
app.createTable();
}
}
So please , Is there any problem with my code .?!
What are the pros and cons of each method ?
which one has a better performence ?
Thanks
The answer depends on whether or not you're going to use the XML as a whole document or not.
If you use XPath to search inside the document parsing and loading might make sense.

Oracle JDBC UCP and Java

I'm wondering if anyone can shed some light on this topic, as I have been racking my brain for days and can't quite understand why this does not work. I have three classes
main, RetrieveDBVersion,GetOracleConnection I've been doing some testing with oracle JDBC, UCP and Java 1.7.
According to the Oracle documentation, If I use connection pooling the connection will be returned to the pool as soon as I close the connection, Invalidate it and set it to null See Here. So I decided to give it a whirl and see if it would perform just like the documentation says it should. In my Main application I have a simple loop which makes a connection 200 times by calling RetrieveDBVersion. RetrieveDBVersion is simply performing a query and returning the driver version. My loop works fine until I hit the magic number of 68 and then I receive an error which states
java.sql.SQLException: Exception occurred while getting connection:
oracle.ucp.UniversalConnectionPoolException:
Cannot get Connection from Datasource: java.sql.SQLException:
Listener refused the connection with the following error:
ORA-12516, TNS:listener could not find available handler with matching protocol stack
These are the detail of the 3 methods. These methods are not in a server environment. They are simply calling a local oracle express database and I'm running them from my desktop. Why would I keep getting this error? If I'm returning the connections back to the pool?
Main
import com.jam.DB.JDBCVersion;
import static java.lang.System.out;
public class MainApp {
public static void main(String[] args) {
String myMainJDBCVar;
try{
for(int i=1; i<200; i++ )
{
myMainJDBCVar= JDBCVersion.RetrieveDBVersion();
out.println(myMainJDBCVar + " " + i);
}
out.println("this is Done!");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
RetrieveDBVersion
import java.sql.*;
import oracle.ucp.jdbc.ValidConnection;
public class JDBCVersion {
public static String DBVersion;
public static String RetrieveDBVersion()throws SQLException {
Connection conn = JDBCConnection.GetOracleConnection("test");
try {
DatabaseMetaData meta = conn.getMetaData();
//get driver info
System.out.println("JDBC driver version is " + meta.getDriverMajorVersion());
DBVersion = meta.getDriverVersion();
} catch (SQLException e) {
e.printStackTrace();
DBVersion = e.getMessage();
}
finally {
System.out.println("hit the finally clause");
((ValidConnection) conn).setInvalid();
conn.close();
conn=null;
}
return DBVersion;
}
GetOracleConnection
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;
import java.sql.*;
public class JDBCConnection {
public static Connection GetOracleConnection(String Enviroment) throws SQLException{
PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource();
Connection conn = null; //ora.defaultConnection();
try {
pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
pds.setURL("jdbc:oracle:thin:#//localhost:1521/xe");
pds.setUser("system");
//pds.setInitialPoolSize(5);
pds.setPassword("xxx");
pds.setMaxStatements(10);
conn = pds.getConnection();
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return conn;
}
So after careful though and getting a little extra help from the Oracle forum. I finally understand why the above referenced code is giving the error message that I'm receiving. See Here For Response
Because I'm setting the data source everytime the loop goes around, I'm essentially creating more than one pool. The way to do this, is create one pool and than pull connections from that pool.
New code to replace the GetOracleConnection I created a singleton class for datasource and in code I simply retrieve the connection from the data source like such
Connection conn = Database.getInstance().GetPoolSource().getConnection();
package com.jam.DB;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;
public class Database {
private static Database dbIsntance;
private static PoolDataSource pds;
private Database() {
// private constructor //
}
public static Database getInstance() {
if (dbIsntance == null) {
dbIsntance = new Database();
}
return dbIsntance;
}
public PoolDataSource GetPoolSource() {
if (pds == null) {
pds = PoolDataSourceFactory.getPoolDataSource();
try {
pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
pds.setURL("jdbc:oracle:thin:#//localhost:1521/xe");
pds.setUser("system");
pds.setPassword("xxxx");
pds.setMaxStatements(15);
return pds;
} catch (Exception e) {
}
return pds;
}
return pds;
}
}

Sqlite cannot insert data when database insider src folder

I spend like 5 hour re-writing all methods cause thought i make mistake while inserting data into DB BUT i noticed everything is fine when i got database outside src folder.
This is my code
public class DataBaseModel {
public static final String DRIVER = "org.sqlite.JDBC";
// public static final String DB_URL = "jdbc:sqlite::resource:sqlite/databse.db"; // insider src/sqlite
public static final String DB_URL = "jdbc:sqlite:database.db";
private Connection conn=null;
private Statement stat=null;
public DataBaseModel() {
try {
Class.forName(DataBaseModel.DRIVER);
} catch (ClassNotFoundException e) {
System.err.println("NO JDBC DRIVER");
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(DB_URL);
stat = conn.createStatement();
} catch (SQLException e) {
System.err.println("Connection problem");
e.printStackTrace();
}
createTables();
}
When i got my project setup like that:
public static final String DB_URL = "jdbc:sqlite:database.db";
everythin work fine:
creating records
display records form db
creating tables
But when i change to
public static final String DB_URL = "jdbc:sqlite::resource:sqlite/databse.db";
there is an error
Connection problem java.sql.SQLException: resource sqlite/database.db not found: java.net.MalformedURLException: no protocol: sqlite/database.db
I get rid of error unconsciously by copping database to src/sqlite thats why i was unable to see any error for all that time ...
Any idea what cause problem when database.db is inside src/sqlite?
I explained as much as i can.
Thx for help

Java and SQL Server

I am new to java, and I am trying to create a method that will retrieve information from the database based on the query that will pass to it.
I thought that I could create by method by creating an object of type:
private Connection controlTableConnection = null;
and then
Statement statement = controlTableConnection.createStatement();
but when I do that piece of code, I get a highlight error:
Unhandled exception
Any help, would be appreciated.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ConnectMSSQLServer {
private static final String db_connect_string = "jdbc:sqlserver://Cdsx\\SQxxs";
private static final String db_userid = "aa";
private static final String db_password = "bb";
private Connection controlTableConnection = null;
public void dbConnect() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection controlTableConnection = DriverManager.getConnection(db_connect_string, db_userid, db_password);
} catch (Exception e) {
e.printStackTrace();
}
}
public void dbDisconnect() {
try {
if (controlTableConnection != null && !controlTableConnection.isClosed()) {
controlTableConnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void createstatement() {
Statement statement = controlTableConnection.createStatement();
}
}
You have to wrap the createStatement line like below, as you have to handle the SQLException.
try {
Statement statement = controlTableConnection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
isn't the Connection null? Do you have a driver on the classpath? is the default port correct? Is the sql server live? What kind of exception do you get exactly?
You need to post at least the stack trace or logs

Java - JDBC executeUpdate() not working

I am trying to insert/update/delete a row using jdbc. Inserting is working, and I only changed the query string (or insertTableSQL) By debugging, I suspect that executeUpdate() is not terminated and console does not show me any error message. (JUST BLANK)
[EDIT]
The program is stuck while executeUpate() is exeucting, meaning that I cannot even see the return value
Instead of using query string, I also tried PreparedStatement but no luck :(
String deleteRecordSQL = "DELETE mytable WHERE id = ?";
PreparedStatement ps = dbConnection.prepareStatement(deleteRecordSQL);
ps.setInt(1, 6);
ps.executeUpdate();
Full Code:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class DeleteRow {
private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DB_CONNECTION = "";
private static final String DB_USER = "";
private static final String DB_PASSWORD = "";
public static void main(String[] argv) {
try {
deleteRecordFromDbUserTable();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void deleteRecordFromDbUserTable() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
statement.executeUpdate("DELETE mytable WHERE id = 6");
System.out.println("Record is deleted!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
Any help?
THIS IS NOT THE OFFICIAL ANSWER, BUT THE PROBLEM IS RESOLVED SOMEHOW
There was Java update notification, and I followed it. After update, the status of JRE System Library(JavaSE - 1.7) is changed to unbound. I changed Execution environment to JavaSE - 1.6 (Oracle WebLogic Server 11gR1 (10.3.6) JRE), and the issue was resolved..weird..
There was no syntax problem
DELETE FROM mytable WHERE id = 6
DELETE mytable WHERE id = 6
If anyone can explain me how this issue could be resolved, your help would be much appreciated.
FYI.
C:\>java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) Client VM (build 24.65-b04, mixed mode, sharing)
Since its stuck it must be waiting for some resource which might be locked.
I had faced this issue for simple update query. Here the update query was run on sql developer tool and the commit was not done.
Thanks to a comment by Prabhmanmeet Singh on this link
If you didn't get an exception, which you don't state one way or the other, you need to examine the return value of executeUpdate(), which is the number of affected rows. If it was zero, no rows were deleted, probably because nothing matched the WHERE clause. If it was non-zero, that many rows were deleted. You certainly shouldn't be printing "Record is deleted!" when nothing may have happened at all. Your program may be lying to the user.
NB insertTableSQL is a stupid name for a variable containing an SQL DELETE statement.

Categories