I am trying to establish a connection to remote mysql db. I have put the jar connector towar/WEB-INF/lib folder and added a library (build path).
Still I am getting this error:
java.sql.SQLException: No suitable driver found for jdbc:sql4.freemysqlhosting.net
at java.sql.DriverManager.getConnection(Unknown Source)
Here is the full code:
/**
*
*/
package com.infograph.dbconnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
/**
* #author Vlad
*
*/
public class DBConnection
{
/**
*
*/
public DBConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try
{
connection = DriverManager.getConnection("jdbc:sql4.freemysqlhosting.net","user", "pass");
}
catch (SQLException e1)
{
System.out.println("Connection Failed! Check output console");
e1.printStackTrace();
return;
}
if (connection != null)
{
System.out.println("You made it, take control your database now!");
}
else
{
System.out.println("Failed to make connection!");
}
}
}
What is the problem?? 10x!
I think what you meant to use is
connection = DriverManager.getConnection("jdbc:mysql://sql4.freemysqlhosting.net","user", "pass");
You possibly need to add a port number and schema name.
The URL you provided, jdbc:sql4.freemysqlhosting.net, is not valid, or at least it doesn't seem like it.
Your connection url must be in form jdbc:mysql://hostname:port/schema in order for DriverManager to determine which driver to use.
Here's more on this:
http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
Related
This question already has an answer here:
Caused by: java.lang.NoSuchMethodError: org.postgresql.core.BaseConnection.getEncoding()Lorg/postgresql/core/Encoding;
(1 answer)
Closed 4 years ago.
CODE:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aaa;
import static aaa.DB.geom;
import static aaa.DB.getConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] argv) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
// Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres", "postgres",
"abc");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
//Connection conn = getConnection();
connection.setAutoCommit(false);
Statement s = null;
try {
s = connection.createStatement();
} catch (Exception e) {
System.out.println("statmnt connection not works");
}
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ss.executeUpdate();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
String query = "CREATE TABLE COMPANY(ID INT );";
ResultSet r = s.executeQuery(query);
connection.commit();
} else {
System.out.println("Failed to make connection!");
}
}
}
RUN:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!
Exception in thread "main" java.lang.NoSuchMethodError:
org.postgresql.core.BaseConnection.getPreferQueryMode()Lorg/postgresql/jdbc/PreferQueryMode;
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:151)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
at aaa.JDBCExample.main(JDBCExample.java:69)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
QUESTION:Give me steps to solve it since database is connected already! What is the core of the problem?
The problem is that if database postgresql connected then why not insert into database. The tables are also available and seen from netbeans. There needs to be a way to solve this run time exception issue when there is a query execution... So I needed step by step details to make it correct.
A SELECT statements has to be executed using executeQuery(). executeUpdate() is for DML statements like UPDATE, INSERT, or DELETE that don't normally return a ResultSet. Also, a DDL statement like CREATE TABLE can not be executed using executeQuery() you need execute() or executeUpdate() for that.
So your code should be:
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ResultSet rs = ss.executeQuery();
while (rs.next() {
// do something
}
rs.close();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
And:
String query = "CREATE TABLE COMPANY(ID INT );";
s.execute(query);
connection.commit();
You have connection.setAutoCommit(false); and you didnt commit after performing update. You have to commit your transaction in order for changes to apply. You can also setAutoCommit(true);
Hi I am trying to connect with Cassandra using jdbc driver. I am getting the following exception.
java.sql.SQLNonTransientConnectionException: Connection url must specify a host, e.g., jdbc:cassandra://localhost:9170/Keyspace1
at org.apache.cassandra.cql.jdbc.Utils.parseURL(Utils.java:190)
at org.apache.cassandra.cql.jdbc.CassandraDriver.connect(CassandraDriver.java:85)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.sub.cas.CqlJdbcTestBasic.main(CqlJdbcTestBasic.java:14)
My cassandra server is running fine and can be accessed from cql shell in windows 10 OS.
This is the java class that I have written.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CqlJdbcTestBasic {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra:/root/root#localhost:9160/hr");
String query = "SELECT empid, emp_first, emp_last FROM User WHERE empid = 1";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("empid"));
System.out.println(result.getString("emp_first"));
System.out.println(result.getString("emp_last"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
con = null;
}
}
}
}
I have gathered my jars from this url :: https://code.google.com/archive/a/apache-extras.org/p/cassandra-jdbc. Unable to find any possible solution. Please help.
Please, check if you have two slashes before your user name. According to
http://www.dbschema.com/cassandra-jdbc-driver.html
I'm trying to do a small application that take some data from a db by connecting to a remote DB2 server using following example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionExample
{
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50000/exampledb";
String user="db2inst1";
String password="password";
Connection connection = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
I get this error:
com.ibm.db2.jcc.am.SqlException: [jcc][10389][12245][3.67.27] Errore nel caricamento della libreria nativa db2jcct2, java.lang.UnsatisfiedLinkError: no db2jcct2 in java.library.path: ERRORCODE=-4472, SQLSTATE=null
further infromation here:
http://www.justexample.com/wp/connect-db2-java/
http://www-01.ibm.com/support/docview.wss?uid=swg21419978
I don't understand where to find missing library, on the JDBC library downloaded from the IBM site is missing, have I to copy it from the remote DB2 server or I have to point to the remote location?
thanks in advance best regards.
I found specific package inside IBM embedded software
I suppose you know how to add a jar file in the library of the app. The driver that you are looking for can be found in the IBM folder that generates when you install DB2.
For the driver go to C:/Program Files/IBM/SQLIB/Java there you can find the db2jcc.
I am creating a simple example of jdbc .I am getting this error .I run my sql server on my mac machine .can you please tell me how to make connection with my sql and remove this error .I already include connector jar file .
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1129)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:358)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2489)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2311)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at HelloWorldExample.main(HelloWorldExample.java:17)
Caused by: java.net.UnknownHostException: local
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:877)
at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1230)
at java.net.InetAddress.getAllByName0(InetAddress.java:1181)
at java.net.InetAddress.getAllByName(InetAddress.java:1111)
at java.net.InetAddress.getAllByName(InetAddress.java:1047)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:248)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:308)
... 15 more
Here is my code ..I am using mac
import java.sql.*;
/**
* HelloWorldExample : JDBC Tutorial that creates a simple database, stores in a single row
* and retrieves the data to then be displayed on standard out. The database is cleaned up
* to reduce clutter for this example.
* Author: Kevin Hooks
* Date: April 18th, 2012
**/
public class HelloWorldExample {
public static void main(String[] args) throws SQLException{
// Note that you can use TCP/IP by using this URL
// "jdbc:raima:rdm://localhost"
// The rdmsqlserver must be running to use TCP/IP
Connection Conn = DriverManager.getConnection("jdbc:mysql://local");
try {
Statement Stmt = Conn.createStatement();
try {
try { //Since the database is created here, it cannot be created twice
Stmt.execute("DROP DATABASE hello_db");
} catch (SQLException exception) {}
Stmt.execute("CREATE DATABASE hello_Db");
Stmt.execute("CREATE TABLE hello_table (f00 char(31))");
Conn.commit();
PreparedStatement PrepStmt = Conn.prepareStatement("INSERT INTO hello_table (f00) VALUES (?)");
try { //Sets parameter value to a string
PrepStmt.setString(1, "Hello World!");
PrepStmt.execute();
Conn.commit();
ResultSet RS = Stmt.executeQuery("SELECT * FROM hello_table");
try {
while(RS.next() != false) {
System.out.println(RS.getString(1));
}
} finally {
RS.close();
}
} finally { //Cleans up by dropping database in this case
Stmt.execute("DROP DATABASE hello_db");
PrepStmt.close();
}
} finally {
Stmt.close();
}
} catch (SQLException exception) {
System.err.println("SQLException: " + exception.toString());
}finally {
Conn.close();
}
}
}
The hostname of the loopback address is localhost, not local.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at HelloWorldExample.main(HelloWorldExample.java:17)
Line 17:
Connection Conn = DriverManager.getConnection("jdbc:mysql://local");
Your program can not establish a connection to the database, be sure that you have your connection URL correct.
local, should be replaced by localhost, or 127.0.0.1
You should also note, that you never actually select a database to use.
you have declared wrong connection string. please modified it according to below rule
Connection Conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name");
your URL should be localhost then add the database name
have a look at this
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class JDBCExample {
public static void main(String[] argv) {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mkyongcom","root", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
I am really new to JAVA but need to call a SQL Server function which I have been given access to.
I have built a JAVA call into a pl/sql function and am successfully calling it from one of my environments. When I move to another environment I get the error
ORA-29532: Java call terminated by uncaught Java exception: java.lang.ClassNotFoundException: com/microsoft/sqlserver/jdbc/SQLServerDriver
I have researched this to death and checked the correct installation of JAVA which seems fine but I'm obviously missing something. I need to somehow trace what is different on this environment, the fact that it runs in the other envionmnet proves that the class is correct so it has to be a config issue.
JAVA Class
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.net.Socket;
import java.io.IOException;
public class xxiceHJ
{
protected static String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
protected static String DB_URL = "jdbc:sqlserver://999.999.99.99:1433";
protected static String USER = "xxxx";
protected static String PWD = "xxxxx123$";
public static String getOrderStatus (String OrderNumber) throws SQLException, Exception
{
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
String Message = null;
String WarehouseId = "01";
try
{
// Register JDBC driver
Class.forName(JDBC_DRIVER);
//Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PWD);
cs = conn.prepareCall("{call usp_get_order_status(?,?,?)}");
cs.setString(1, WarehouseId);
cs.setString(2, OrderNumber);
cs.setString(3, Message);
rs = cs.executeQuery();
//if prodeure return a value
if (rs.next())
{
Message = rs.getString(1);
}
//Clean-up environment
rs.close();
cs.close();
conn.close();
// }
// catch (SQLException se)
// {
// //Handle errors for JDBC
// cfFileNumber = "SQLException" + se.toString();
// se.printStackTrace();
// }
// catch (Exception e)
// {
// //Handle errors for Class.forName
// cfFileNumber = "Exception" + e.toString();
// e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if (rs!=null)
{
rs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (cs!=null)
{
cs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (conn!=null)
{
conn.close();
}
}
catch (SQLException se)
{
se.printStackTrace();
}
}
return Message;
}
}
The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer. If the drivers are not listed in your CLASSPATH variable, you receive the following error message when you try to load the driver:
java.lang.ClassNotFoundException: com/microsoft/jdbc/sqlserver/SQLServerDriver
The JDBC driver is not part of the Java SDK. If you want to use it, you must set the classpath to include the sqljdbc.jar file or the sqljdbc4.jar file. If the classpath is missing an entry for sqljdbc.jar or sqljdbc4.jar, your application will throw the common "Class not found" exception.
The sqljdbc.jar file and sqljdbc4.jar file are installed in the following location:
\sqljdbc_\\sqljdbc.jar
\sqljdbc_\\sqljdbc4.jar
The following is an example of the CLASSPATH statement that is used for a Windows application:
CLASSPATH =.;C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc.jar
The following is an example of the CLASSPATH statement that is used for a Unix/Linux application:
CLASSPATH =.:/home/usr1/mssqlserverjdbc/Driver/sqljdbc_4.0/enu/sqljdbc.jar
You must make sure that the CLASSPATH statement contains only one Microsoft JDBC Driver for SQL Server, such as either sqljdbc.jar or sqljdbc4.jar.
For more information, please see:
http://support.microsoft.com/kb/313100
http://msdn.microsoft.com/en-us/library/ms378526.aspx
first Please download correct sql driver and then check your are using correct connection driver as per operating system. then once you have to test your connection if its working fine then you will go to next .
so please check this url
microsift sql server driver for linux
https://msdn.microsoft.com/en-us/library/hh568451(v=sql.110).aspx
my sql server driver for linux
https://dev.mysql.com/downloads/connector/j/5.0.html