Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I trying make connection between Mysql and my java program
My system configuration is:
Windows :10
64 bit
java version: 1.8
jar file: mysql-connector-java-8.0.19
My source code:
DatabaseConnectivity.java
package test;
import java.sql.*;
public class DatabaseConnectivity
{
Connection conn;
Connection getConnection(String database,String userName,String password)
{
try{
String url;
url="jdbc:mysql://localhost:8080/"+database;
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn=DriverManager.getConnection(url,userName,password);
System.out.println("Connected to database successfully");
}
catch(Exception e)
{
System.out.println("Error occured"+e);
}
return conn;
}
public DatabaseConnectivity()
{
}
}
Test.java
package test;
import java.sql.*;
import test.*;
class Test
{
public static void main(String args[])
{
try
{
DatabaseConnectivity db=new DatabaseConnectivity();
Connection conn=db.getConnection("records","root","dics");
System.out.println("Connected to database successfully");
}
catch(Exception e)
{
System.out.println(" Error occured"+e);
}
}//End of main method
}//End of class Test
I have set my classpath as
>set classpath
classpath="E:\softwares\java\jar files\mysql-connector-java-8.0.19.jar;";
I tried to run my code
javac DatabaseConnectivity.java
javac -classpath e:\user\java\jdbc\ Test.java
java -classpath e:\user\java\jdbc\ test.Test
It throws error
Error occuredjava.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Connected to database successfully
There were few problems.
The problem was when I set classpath by environment variables. And pass -classpath variable it overrides the default classpath environment variable.
So add jar file path to classpath option passed with java.exe
Class.forName() is not used anymore in mysql(mysql-connector-java-8.0.19). I
don't know why?
Source code:
E:\user\java\jdbc\test\DatabaseConnectivity.java
package test;
import java.sql.*;
public class DatabaseConnectivity
{
Connection conn;
Connection getConnection(String database,String userName,String password)
{
try{
String url;
url="jdbc:mysql://localhost:3306/"+database;
//Class.forName("com.mysql.jdbc.Driver");
//Class.forName("com.mysql.cj.jdbc.Driver");
conn=DriverManager.getConnection(url,userName,password);
System.out.println("Connected to database successfully");
}
catch(Exception e)
{
System.out.println("In Class DatabaseConnectivity Error occured"+e);
}
return conn;
}
public DatabaseConnectivity()
{
}
public static void main(String args[])
{
}
}
E:\user\java\jdbc\test\Test.java
package test;
import java.sql.*;
import test.*;
class Test
{
public static void main(String args[])
{
try
{
DatabaseConnectivity db=new DatabaseConnectivity();
Connection conn=db.getConnection("test","root","dics");
Statement st = conn.createStatement();
String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
}
catch(Exception e)
{
System.out.println(" class Test Error occured"+e);
}
}//End of main method
}//End of class Test
Third problem, I was using mysql 8+ and my jar file version was 5+. Your mysql version and jar file version should be same. Now, It is 8 as you can see in the classpath.
Check the port number of mysql
Login to mysql -u root -p
mysql>show variables where variable_name="port";
It was 3306. As you can see in my question I was usnig default port number which is 8080. I must have changed it while mysql installation because some other application was already running on 8080(probably tomcat or wamp server).
To execute
E:\user\java\jdbc\test>javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; DatabaseConnectivity.java
E:\user\java\jdbc\test>javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; Test.java
E:\user\java\jdbc\test>java -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; test.Test
Connected to database successfully
Table creation process successfully!
Related
I'm new to setting up connections to mysql servers, I have already defined a database, and set up tables within it, but I am having issues with connecting to it.
It seems that it is not executing the statement at all, and is throwing an error every time I try it.
import java.sql.*;
public class initDB {
public static void main(String[] args) throws Exception{
Connection dbcon = null;
try {
System.out.println("tried try statement");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("tried driver");
dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/raindatabase", "user", "loginsystem"
);
System.out.println("tried to get connection");
} catch (Exception e){
e.printStackTrace();
}
}
}
It throws this error message:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:291)
at initDB.main(initDB.java:10)
MySQL connector JAR should be in your class path.
This tutorial will help to understand JDBC connections https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-connect-drivermanager.html
You can download connector from here https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-installing.html
In IntelliJ, you can add jar to library. File -> Project Structure -> Libraries -> {Add your jar}
or, To compile/run from command:
Compile:
javac -classpath PATH_TO_MYSQL_CONNRECTOR_JAR;%CLASSPATH% YOUR_JAVA_FILE.java
Run
java -classpath PATH_TO_MYSQL_CONNRECTOR_JAR;%CLASSPATH% YOUR_JAVA_CLASS_FILE_NAME
I am using jdk1.8 and I am trying to execute a jdbc program manually on oracle 8i. My code is compiling without any error but at the run time its showing error-no suitable driver found for jdbc:oracle:thin:#localhost:1521:orcl. I have already set the class path for jar file. I am using ojdbc7.jar file.
My code is:
import java.sql.*;
class Database
{
public static void main(String arg[])
{
try
{
String url="jdbc:orcl:thin:#localhost:1521:orcl";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,"scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from aj1");
while(rs.next())
{
System.out.println("\n"+rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e){e.printStackTrace();}
}
}
Kindly give the solution for this:
You url String must be
String url="jdbc:oracle:thin:#localhost:1521:orcl";
instead of
String url="jdbc:orcl:thin:#localhost:1521:orcl";
and try.
I'm trying to connect my DB with a Java Application i'm creating. What I got so far:
public class DBConnect {
public void DBConnect() {
try {
DBConnect DBConnect = null;
String url = "jdbc:mysql://localhost:3306/ähs_system";
String uName = "**";
String uPass = "**";
// Connection conn = DriverManager.getConnection(url, uName, uPass);
System.out.println("DB Connected");
}
catch (Exception Err) {
System.out.println("Error while connecting: " + Err.getMessage());
System.exit(0);
}
}
}
It's a runnable code although i'm still able to run the code without any error messages if I change my uName and/or Upass. So based on that information i'm gonna say that it's not actually connecting to the database at all...
Anyone with a few tips or tricks I can use?
I've loaded the DB in services and I am able to reach it and add data and run other SQL commands within netbeans but that's basically it. I've also loaded the mysql-connector-java-5.1.35 driver.
Run Code:
public static void main(String args[]) {
try {
DBConnect DBConnect = new DBConnect ();
DBConnect.DBConnect();
}
catch (Exception e){
System.out.println("Cannot connect to DB. Error: " + e.getMessage());
}
Let me know if you need any furthur information!
Updating property file: C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\built-jar.properties
Compiling 1 source file to C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\classes
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\src\kiltenros\DBConnect.java:23: error: incompatible types: java.sql.Connection cannot be converted to kiltenros.Connection
Connection conn = DriverManager.getConnection(url, uName, uPass);
1 error
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:923: The following error occurred while executing this line:
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:263: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
the error log is clear
java.sql.Connection cannot be converted to kiltenros.Connection
it seems that you imported the wrong class in the beginning of your class
DriverManager.getConnection(url, uName, uPass) return you instance of java.sql.Connection.
btw, change your local variable DBConnect to dbConnect so it won't has the same name as your class DBConnect and it will follow the java convention (lowercase on 1st letter of a variable)
I've very little experience with MySQL, but I avoid using "ä" in a database name. Perhaps, the underscore isn't allowed.
As per your stacktrace it seems you have not imported the correct Connection class. Delete the Connection file in your project and import java.sql.Connection.
The problem seemed to be a corrupted rs2xml.jar file. Once I reloaded it and it worked.
my code is
import java.sql.*;
public class SelectTest{
public static void main(String arr[]) {
try {
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:myDb","system","oracle");
Statement stmt=con.createStatement();
ResultSet rset=stmt.executeQuery("select * from emp");
while(rset.next()) {
System.out.print(rset.getInt(1)+"\t"+rset.getString(2)+"\t"+
rset.getString(3)+"\t"+rset.getInt(4));
}//while loop
con.close();
}//try
catch(Exception ex) {
System.out.print(ex);
}//catch
}//main
}//class
And i set classpath of the oracle DB in system environment as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.
And i set path for jre in user variables as
C:\Program Files\Java\jdk1.7.0_17\bin;.;
i am not getting why my program is giving the error:
Error: this program is not recognised as internal or external command.
You probably won't have jre and jdk installed. If java -version has the same result install these.
I've set the classpath envoirenment but still get an error "Exception:com.mysql.jdbc.Driver"
Do you have any idea what might be wrong?
Here is my test code:
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}
Exception:com.mysql.jdbc.Driver
Is most probably not the full error message. I guess it's a ClassNotFoundException and you simply do not have the MySQL JDBC driver as part of your classpath.
When running your program, you need to list the driver as well
java -cp .;mysql-connector-java-5.1.7-bin.jar JdbcExample1
(This assumes JdbcExample1.class and the .jar file are in the current directory)
I've set the classpath envoirenment
Setting the CLASSPATH environment variable is not necessary anymore (actually it never has been necessary). As a matter of fact it creates more problems than it solves.
Use the above syntax to supply the path to your driver and run your program
As horse says, I'm pretty sure it's a 'ClassNotFoundException'.
To be sure add "e.printStackTrace();" in your catch-block.
Always best to get a stack trace.