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
Related
I wanted to connect to an Oracle database using JDBC.
I installed ojdbc6.jar properly and wrote this code.
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnect {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.OracleDriver");
String url = "jdbc:oracle:thin:#192.168.127.129:1521:helowin";
String id = "msa_checkin";
String pass = "msa0526";
Connection con = DriverManager.getConnection(url, id, pass);
if(con != null)
System.out.println("Oracle success");
else
System.out.println("Oracle failed");
}
catch(Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
}
But the output looks like this.
Error
java.sql.SQLException: Undefined Error
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:412)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:531)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:221)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:503)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.kinth.DBConnect.main(DBConnect.java:14)
Caused by: oracle.net.ns.NetException: Undefined Error
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:385)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1042)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:301)
... 7 more
I search for similar questions,but it doesn't solve my problem.
Unable to get Oracle database connection, should I format my computer?
No problem with Navicat.
Navicat Image
I tried using oracle6.jar and Oracle14.jar but neither worked.
Can you follow the instructions on this page and try to get a connection using the latest JDBC drivers?
I already saw many post where people were trying to add the driver. I'm using intelij as IDE and added the driver under Modules => Dependencies => Add Jar; So my IDE identified the driver and can show me the source file of it. My problem is, as soon i start my server I'll get that error that he couldn't find the driver:
My Code:
private void createDB()
{
try {
Class.forName("com.mysql.jdbc.Driver");
database = DriverManager.getConnection("jdbc:mysql://***:" + 3307 + "/**db", "", "");
} catch (Exception e) {
e.printStackTrace();
}
}
My exception:
> java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
I have a class that tries to connect to a Heroku database:
public class ConnectionFactory {
public Connection getConnection() {
System.out.println("Conectando ao banco");
try {
return DriverManager.getConnection("connectionstring", "username", "password");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
What it returns is:
java.lang.RuntimeException: java.sql.SQLException: No suitable driver
found for
jdbc:postgres://osnvehqhufnxzr:TS3Qt37c_HHbGRNKw3yk7g88fp#ec2-54-225-93-34.compute-1.amazonaws.com:5432/d39mfq0odt56bv
I already tried postgresql-9.3-1103.jdbc3.jar and postgresql-9.4.1209.jre6.jar
in the Build Path of the project. What I am doing wrong?
Use postgresql in your JDBC URL and not postgres.
Also, you need to change your DB password (because you posted it publicly) by running this command:
$ heroku pg:credentials DATABASE --reset
You need to load the driver class first by the class loader:
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(...);
Also see: What is the purpose of 'Class.forName("MY_JDBC_DRIVER")'?
The solution was simple, System.getenv("JDBC_DATABASE_URL") returns it in server and it does the correct configuration of login and password.
public Connection getConnection() throws URISyntaxException, SQLException
{
String urlDB = System.getenv("JDBC_DATABASE_URL");
return DriverManager.getConnection(urlDB);
}
This is an issue that has come up before on SO, and I'm sure seasoned Java devs are tired of telling newbies howto set the classpath. That said, I've tried setting the classpath via environment variable and with the -cp option, with no success.
I'm using the sample applications that are bundled with the SQLServer JDBC driver. I'm running Ubuntu 14.10. I compile the app on the command line:
javac -cp .:/path/to/sqljdbc42.jar connectURL.java
and the run it:
java connectURL
which gets me the familiar ClassNotFoundException:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at connectURL.main(connectURL.java:42)
I haven't modified the sample class file, but I'm including it here for completeness:
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
The path to the SQL JDBC .jar is definitely correct. If I add import com.microsoft.sqlserver.jdbc.SQLServerDriver; to the class file I don't get any complaints when compiling, but still get the ClassNotFoundException at runtime.
I've read elsewhere that newer versions of the JDBC don't need you to load drivers via Class.forName, but if I remove that line then I get, predictably, java.sql.SQLException: No suitable driver found.
What am I doing wrong? I'm sure the .jar is being loaded and the class is being found, because if I try e.g. import com.microsoft.sqlserver.jdbc.SomeNonExistentClass; I get:
connectURL.java:2: error: cannot find symbol
My Java details:
$ java -version
java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-0ubuntu0.14.10.2)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)
You're halfway there. You include the JDBC JAR on your classpath when you compile, but you also need to include it on your classpath when you execute it as well:
java -cp .:/path/to/sqljdbc42.jar connectURL
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.