connectivity error in DERBY - java

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");

Related

connect to database using JDBC in java

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)))

Connecting Java to mysql Error

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.

The service class "WBSer_RwCnt.Rw_Count" does not comply to one or more requirements of the JAX-RPC 1.1 specification

package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
Class.forName(driver); // load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
String tableName = "hospital_status";
System.out.println("tableName=" + tableName);
System.out.println("conn=" + conn);
System.out.println("rowCount=" + countRows(conn, tableName));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Error --->
The method "getConnection" on the service class "WBSer_RwCnt.Rw_Count" uses a data type, "java.sql.Connection", that is not supported
When i compile it without creating it as webservice it works correctly
but when i make it as web service it gives output as
Output --->
WBSer_RwCnt.Rw_CountSoapBindingStub#121a412b
Please Help !
Next Try
So this is what i have done after what you have said even then it gives following errors
Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
Message:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static int countRows() throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
System.out.println("ram");
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
try {
Class.forName(driver);
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM hospital_status");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
finally {
rs.close();
stmt.close();
conn.close();
}
return rowCount;
}
}
i have the added all jar files including the java mysql connectors
This is not going to be a full answer as I'm not exactly sure about the tools you are using to compile the web service, but anyway, here goes:
Basically, a connection is something that is only valid on a particular machine. If it's a TCP/IP connection, it consists of two pairs: source host and port, and target host and port. If it's a Linux socket, then it is an entry in that particular machine's directory tree.
A database connection is usually built on one of those constructs, so it, too, is particular to a machine.
Therefore, it doesn't make sense to pass a Connection object to the user who calls your method from some remote machine. And since it doesn't make sense, the JAX-RPC standard does not include a serialization for Connection, and that's why it fails.
Your problem is that you have designed your method such that it accepts a connection as a parameter, and uses that connection to access the database. This works OK locally, but is not a good design for a remote service.
Instead, your method should acquire the connection internally. The remote user should access just the countRows method, with the name of the table, and countRows should call getConnection, use the connection, and the close it.
You shouldn't have a main method in a web service. And the getConnection method should be changed from public to private, so that countRows can access it. When it is private, I believe the web service compiler will not complain about it because it doesn't have to create a serialization for it.

java.sql.SQLException: Invalid handle

I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'

How can I insert data from a connection to other connection?

I want to insert data from a table which connection is oracle to another table which connection is mysql. I use netbeans and jdbc driver.
Is it possible? I mean how can I do select data from A table (X connection) and insert B table (Y connection)
connection X = DriverManager.getConnection("jdbc:oracle:thin:#" + host__ + ":" + port__ + servic, props);
connection Y = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
conn.close();
Thank you.
Here is a small example that copies a database table to another database.
You just need two connections conf(rom) and cont(o). You will need to modify both getConnection parameters, table names and field types.
// Copy
Statement stf, stmt;
Connection conf, cont;
ResultSet rsf, rs;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.jdbc.Driver");
conf = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:" + databaseFrom, "user1", "passwd1");
try {
stf = conf.createStatement();
rsf = stf.executeQuery("select * from supplier order by sname");
// read from rsf write to rs!
cont = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + databaseTo, "user2", "passwd2");
stmt = cont.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select * from supplier order by sname");
while (rsf.next()) {
rs.moveToInsertRow();
rs.updateInt(1, rsf.getInt(1));
rs.updateString(2, rsf.getString(2));
rs.updateString(3, rsf.getString(3));
rs.updateString(4, rsf.getString(4));
rs.updateInt(5, rsf.getInt(5));
rs.updateString(6, rsf.getString(6));
rs.updateInt(7, rsf.getInt(7));
rs.updateDouble(8, rsf.getDouble(8));
rs.updateString(9, rsf.getString(9));
rs.insertRow();
}
} catch (SQLException s) {
JOptionPane.showMessageDialog(this, "problem creating database " + s);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getStackTrace());
} finally {
if (stf != null) {
try {
stf.close();
stmt.close();
} catch (SQLException e) {
// handle Exception
}
}
if (conf != null) {
try {
conf.close();
cont.close();
} catch (SQLException e) {
// handle Exception
}
}
}
You can create two classes for different connection:
public class OracleConnectionManager {
public static Connection getOracleConnection() throws SQLException, ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:oracle","username","password");
return connection;
}
}
public class MySqlConnectionManager {
public static Connection getMySqlConnection() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306:mysql","username","password");
return connection;
}
}
Now you can use these classes to get the specific connections and do whatever you want.
You can get the oracle database connection and get the oracle statement > Resultsset, iterate over it
and insert the data into mysql.
Please let me know in case more information is required.
Follow these steps:
Connect to the Oracle database with one data access class
Connect to the MySQL database with a different data access class
Read row(s) from a table in the Oracle database
Perform any column transformations
Write row(s) to a table in the MySQL database
Close the database connections

Categories