This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
I am trying to connect to data base.Earlier it was working fine. but now some jars has got deleted or something I don't know (red cross were coming on them). But I downloaded all jars again (mysql-connector,commons-io-2.4)still I am getting classnotfound exception at Class.forName("com.mysql.jdbc.Driver");
Here is my code
package abc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC_oracle {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1 load the driver class
Class.forName("com.mysql.jdbc.Driver");
//step2 create the connection object
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","user_name", "pswrd");
//step3 create the statement object
Statement statement = connection.createStatement();
statement.executeUpdate("sql_query");
ResultSet rs=statement.executeQuery("sql_query");
while(rs.next())
System.out.println("I am triyng to print data");
//step5 close the connection object
connection.close();
}
}
This is error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at deiniteguide.JDBC_example.main(JDBC_example.java:24)
I have tried using try catch also it is not working for me.
If you are using netbeans, you can go to your library folder in your project. Right click and add library and select mysql driver. Sorry couldn't comment due to less reputation and it would be easier if you can post with what error message you get. Also use try catch in your program so that it will be easier to locate the error. Your code can be like this:
public class JDBC_oracle {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1 load the driver class
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.println("Class not found" +e);
//step2 create the connection object
try{
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","user_name", "pswrd");
}catch(Exception es){
System.out.println("connection couldn't be made "+es);
}
//step3 create the statement object
try{
Statement statement = connection.createStatement();
statement.executeUpdate("sql_query");
ResultSet rs=statement.executeQuery("sql_query"); }
catch(Exception er){
System.out.println("Query wasnot executed "+er);
}
while(rs.next())
System.out.println("I am triyng to print data");
//step5 close the connection object
connection.close();
}
}
Related
I am trying to connect sqlite db browser with java using nano editor i am very new here. i have
followed some youtube videos but i am stacking at mid can anyone please help
here is my code.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SqliteDB{
Connection c = null;
Statement stmt = null;
SqliteDB(){
try{
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:signup.db");
System.out.println("Connected to DB");
}
catch(Exception e){
System.out.println("Error: "+ e.getMessage());
}
}
}
Error: org.sqlite.JDBC
thank you guys for helping.
I think that you have not imported library org.sqlite.JDBC in your project, Class.forName() return class that exists, when you get error like this it says that this class is not exists.
First of all download library from: https://bitbucket.org/xerial/sqlite-jdbc/downloads/
Then import in your project and that's how you should write the code:
public static void main(String[] args) throws SQLException {
org.sqlite.JDBC j = new org.sqlite.JDBC();
Connection c = DriverManager.getConnection("jdbc:sqlite:signup.db");
//do stuff here
}
Getting error while trying to connect to SQL Server 2014.
I'm using JRE7 and sqljdbc4-4.0.jar
here is my java code:
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Testing {
public static void main(String[] args) {
String url = "jdbc:sqlserver://localhost:1433;databaseName=test;encrypt=false";
String user = "sa";
String pass = "";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e);
}
try (Connection con=DriverManager.getConnection(url,user, pass);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM exts WHERE ext = 1001");){
if(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
} else {
System.out.println("NOT_FOUND");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Here is the full stack trace:
java.ext.dirs: C:\Cisco\CallStudio\eclipse\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SQL Server did not return a response. The connection has been closed. ClientConnectionId:dd9cabc2-3683-4a14-857c-eeefd2751853".
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1668)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1323)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.test.Testing.main(Testing.java:32)
Caused by: java.io.IOException: SQL Server did not return a response. The connection has been closed. ClientConnectionId:dd9cabc2-3683-4a14-857c-eeefd2751853
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.ensureSSLPayload(IOBuffer.java:651)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.readInternal(IOBuffer.java:708)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.read(IOBuffer.java:700)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.readInternal(IOBuffer.java:895)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.read(IOBuffer.java:883)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.read(InputRecord.java:480)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1618)
... 7 more
SSL exceptions occur when TLS version mismatch. As you are using Java 7, Try to add sslProtocol=TLSv1.2 to your connection string.
thanks for any help, I am a complete noob here but trying to learn.
the below code is simply trying to create a connection to a database. I am getting this error back:
java.lang.ClassNotFoundException: org.postgres.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at CreateDB.main(CreateDB.java:11)
java.lang.ClassNotFoundException: org.postgres.Driver
having researched online the solution i come across is to check the library is added to to build path. i can confirm that i have (I think). to do this i right clicked the prject -> Properties -> Java Build Path -> external JARS and navigated to the postgresql - 42.41.4..jar which is located in "...\eclipse-workspace\libraries\"
I can see that the library is added under referenced libraries within the project.
not a clue now im stuck. any help is genuinely appreciated.
I am learning from here https://www.tutorialspoint.com/postgresql/postgresql_java.htm
import java.sql.Connection;
import java.sql.DriverManager;
public class CreateDB {
public static void main(String Args[]) {
Connection c = null;
try {
Class.forName("org.postgres.Driver");
c = DriverManager.getConnection("jdbc.postgresql://localhost:1080/VEM", "postgres", "Diablo12" ); //creates connection with U&P
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() +": " + e.getMessage());
System.exit(0);
}
System.out.println("Database opened successfully");
}
}
The correct driver name is: org.postgresql.Driver. So your code should look like this:
import java.sql.Connection;
import java.sql.DriverManager;
public class CreateDB {
public static void main(String args[]) {
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc.postgresql://localhost:1080/VEM", "postgres", "Diablo12" ); //creates connection with U&P
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() +": " + e.getMessage());
System.exit(0);
}
System.out.println("Database opened successfully");
}
}
The false driver name causes java to throw the ClassNotFoundException because the class with the passed name could not be found in the classpath.
Since Java 6 the loading of the driver via Class.forName() is not needed any more, like a_horse_with_no_name pointed out in his comment.
I have SQL server on a machine under the domain DOM005 and I am trying to connect to it using JDBC driver from my local machine that is in another domain. I am using windows authentication for the connection through domain administrator account.
I cannot use "integratedSecurity=true" in my connection URL since both machines are in different domain. Hence I use "authentication=ActiveDirectoryIntegrated" but I am getting the following error:
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'DOM005\administrator'. ClientConnectionId:84224bcd-d2f1-4386-aadf-397c1ef3eadf
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:251)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:3077)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2360)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2346)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1404)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1068)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:904)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:451)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1014)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at TestJDBCsqlServer.main(TestJDBCsqlServer.java:23)
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestJDBCsqlServer {
private static final String SQLSERVER_URL_NTLM = "jdbc:sqlserver://10.20.13.4:1433;databaseName=DB1;authentication=ActiveDirectoryIntegrated";
public static void main(String[] args) throws Exception {
boolean isNTLM = true;
Connection conn = null;
Statement stmt = null;
if(isNTLM){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(SQLSERVER_URL_NTLM, "DOM005\\administrator", "abc");
stmt = conn.createStatement();
ResultSet set = stmt.executeQuery("select 1");
System.out.println("NTLM connection is successful");
set.next();
System.out.println(set.getString(1));
}finally{
if(stmt != null)
stmt.close();
if(conn!=null)
conn.close();
}
}
}
}
Can anyone help me resolve the issue?
I am trying to fetch data from my Online database, but following error is coming. However it is working fine for my local database.
Java Code
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.sql.*;
import javax.swing.JOptionPane;
public class BankingSystem extends JFrame {
public static void main(String[] args) throws Exception
{
int ur=0;
int PIN;
String ID;
int userSelection=0;
Boolean pinCorrect = false;
int amountDeposite;
int amountWithdraw;
int updateResult;
Boolean isExit=false;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://mysql11.000webhost.com/a46854323_javaapp";
String user = "a46854323_javaapp";
String pass="password";
Connection con = DriverManager.getConnection(url,user,pass);
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
}
and I get the following error:
`
Exception in thread "main" java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.ConnectException: Connection timed out: connect
java.net.SocketException
MESSAGE: java.net.ConnectException: Connection timed out: connect
STACKTRACE:
java.net.SocketException: java.net.ConnectException: Connection timed out: connect at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at BankingSystem.main(BankingSystem.java:22)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1875)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at BankingSystem.main(BankingSystem.java:22)
What can be the solution ?
I have gone through all the comments above and found that 000host.com doesn't provide the facility that its database can get accessed by outside its own space. So with little googling i found http://www.db4free.net that provide free mySql database for testing purpose. And in this way my problem get solved. Thanks to all comentators.