I'm fairly new to database management. I'm just trying to connect to the database and retrieve and display a table in the command prompt. The database is not on my computer. I am fairly certain that the url is the problem. The code:
import java.io.*;
import java.sql.*;
class transfer{
//driver and DB URLs
final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
final static String DB_SQL = "jdbc:microsoft:sqlserver://localhost:1433;" + "database=DataDB;" + "user=sa;" + "password=1234";
//Database Username and password
final static String user1 = "sa";
final static String pass1 = "1234";
static ResultSet rs;
public static void main(String args[]) throws SQLException, ClassNotFoundException{
Connection conn_sql = null;
Statement stmt_sql = null;
//Statement stmt_ora = null;
//Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Open Connection
System.out.println("Connecting to SQL database...");
conn_sql = DriverManager.getConnection(DB_SQL, user1, pass1);
//Execute Query
String sql_query;
System.out.println("Creating statement for SQL...");
stmt_sql = conn_sql.createStatement();
sql_query = "Select * from attendancesummary";
rs = stmt_sql.executeQuery(sql_query);
System.out.println("SQL table details");
System.out.println("Creating statement for SQL...");
while(rs.next()){
//Retrieve data
int cno = rs.getInt("CardNo");
int in_time = rs.getInt("entry");
int out_time = rs.getInt("Exittm");
String name = rs.getString("Name");
int date = rs.getInt("TrDate");
//Display data
System.out.print("Employee ID: "+cno);
System.out.print("\tName: "+name);
System.out.print("\tDate:"+date);
System.out.print("\tEntry: "+in_time);
System.out.print("\tExit: "+out_time);
}
}
}
The database name is DataDB and the table that I want to retrieve and display is attendancesummary. I have set my path as "C:\Program Files\Java\jdk1.8.0_11\bin";"C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar"
The code compiles fine.. but when I run it, I get the following error:
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run
at java.net.URLClassLoader$1.run
at java.security.AccessController.doPrivileged
at java.net.URLClassLoader.findClass
at java.lang.ClassLoader.loadClass
at sun.misc.Launcher$AppClassLoader.loadClass
at java.lang.ClassLoader.loadClass
at java.lang.Class.forname0
at java.lang.Class.forname
at transfer.main
I am truly lost. Any help would be appreciated!
It means that sqljdbc4.jar is missing from your CLASSPATH while running the code. If you are running this from command line then add the path to sqljdbc4.jar in -cp switch of java command.
If you are running from eclipse, then add sqljdbc4.jar in your build path.
Add sqljdbc4.jar in your classpath.
If you are using Eclipse then you can right click on project -> properties -> java build path.
Go to libraries and click on add external jar.
Then add the jdbc driver jar.
Hope this helps.
You have to add the JDBC driver to your project class path: example if you are using Eclipse put the jar in the 'lib' folder
Related
This question already has answers here:
How do I resolve ClassNotFoundException?
(28 answers)
Closed 2 years ago.
This is the code I've written:
package JDBC;
import java.sql.*;
public class JDBC {
public static void main(String[] args) {
try{
String driverName = "org.apache.derby.jdbc.ClientDriver";
String dbURL = "jdbc:derby://localhost:1527/Student";
String dbUser = "DV";
String dbPass = "Pass";
Class.forName(driverName);
Connection con = DriverManager.getConnection(dbURL, dbUser, dbPass);
Statement stmt = con.createStatement();
String sql;
sql = "create table Student(Enroll_No Varchar(20), Name Varchar(20), Gender Char, Age Int, CGPA Float, Email_ID Varchar(30))";
stmt.executeUpdate(sql);
stmt.close();
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
The error I'm getting is:
run:
java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver
BUILD SUCCESSFUL (total time: 0 seconds)
and no table is created. I'm using Glassfish 4.1.1(Derby Database) on NetBeans IDE 8.2
For a ClassNotFoundException, you might want to check about missing .jar files in your project library.
Go to your Project Folder on Netbeans (top left corner), then Libraries and then check for "derbyclient.jar" and "derby.jar" files.
If they are not present, add them manually from your GlassFish folder.
Right click on Libraries -> Add JAR/Folder... Browse to your Glassfish 4.1.1 installation folder -> javadb -> lib and select derbyclient.jar and derby.jar files.
This should work and the exception shall be removed.
I would like to use my MariaDB database but I get the error message:
java.lang.ClassNotFoundException: org.mariadb.jdbc.Driver
My pom.xml includes:
<dependencies>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
Also I have downloaded the file mariadb-java-client-2.4.1-sources.jar and placed it into WEB-INF/lib.
Database.java
package ch.yourclick.zt;
import java.sql.*;
public class Database {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// Ensure we have mariadb Driver in classpath
Class.forName("org.mariadb.jdbc.Driver");
// create our mysql database connection
String host = "localhost";
String dbname = "zt_productions";
String url = "jdbc:mariadb://" + host + "/" + dbname;
String username = "root";
String password = "test";
Connection conn = DriverManager.getConnection(url, username, password);
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM users";
// create the java statement
Statement st = conn.createStatement();
st.close();
}
}
I also tried it with Class.forName("org.mariadb.jdbc.Driver").newInstance();.
No matter what I try, I always get the same error message. Any help would be appreciated.
You are using the wrong jar file. The source won't help you out.
Instead of mariadb-java-client-2.4.1-sources.jar, try using mariadb-java-client-2.4.1.jar.
I had this Problem myself:
the solution was quite simple... MariaDB is basically still MySQL. In the Url you are using to connect to the Database (jdbc:mariadb://localhost:3306) you can therefore just use jdbc:mysql://localhost:3306 <- i just replaced mariadb with mysql. It is still running on a mariadb server but it works so dont change it ;)
I have been starting off with some JDBC a few days ago as of 2019/3. And there was this error occurring when I try to comply the code below in my eclipse IDE.
I actually did some research before this and I have tried:-
-Adding external libraries from the project menu
-Reinstalling and trying out different ides(thinking it was just eclipse but turns out its something about my system)
-reinstalled both jdk and the jdbc connector
and still, the problem persists.
import java.sql.*;
public class Driver{
public static void main(String[]args)throws Exception {
String url = "jdbc:mysql://localhost:3306/main";
String uName = "Ng Jun Han";
String pW = "password";
String query = "SELECT first FROM students WHERE id = 1";
Class.forName("com.sql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uName, pW);
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
rs.next();
String name = rs.getString("first");
System.out.print(name);
st.close();
con.close();
}
}
This is how my project directory looks like
My biggest concern regarding the topic is about something wrong I did with the installation methods. Mainly because there are not much up-to-date resources to follow.If so, does anyone know the CORRECT way of fixing it?(the driver jar file is located at C:\Program Files\MySQL , and i c/p-ed it into my the libraries file in my project directory) Thanks for helping:)
Try this class name :
Class.forName("com.mysql.cj.jdbc.Driver")
Refer to the official docs
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 3 years ago.
The code below is exactly the same from a YouTube video, but it does not work for me. The expected output is to printout "connected" to the system, which means that JDBC is successfully connected to the database. But I get this error:
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.
Here is my code:
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Controller {
private static final String username = "root";
private static final String password = "";
private static final String connection = "jdbc:mysql://localhost/hello";
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection(connection, username, password);
System.out.println("Connected");
}
catch (SQLException se) {
System.err.println(se);
}
}
}
I've added the JDBC successfully as a library, exactly like the video showed but it doesn't work. I saw similar questions on Stack Overflow but none of them solved my problem. Any help will be appreciated, thanks!
JDBC version: mysql-connector-java-5.1.47-bin.jar
Link failure means DB is not reachable, Kindly confirm your DB host,
port, username and password. If everything is correct, kindly confirm
DB server is running and has yet to hit max connection limit.
and you are using JDBC jar file, this may be corrupted. so check it and I suggest you, import JDBC using Maven
and you did not register JDBC driver. first, register it
by using Class.forName("com.mysql.jdbc.Driver"); this
here is one example for your help,
// 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);
}
I assumed you put the appropriate JDBC dependency in your maven file
and use com.mysql.cj.jdbc.Driver as class for newer versions of MySQL-connector
The name of the class that implements java.sql.Driver in MySQL
Connector/J has changed from com.mysql.jdbc.Driver to
com.mysql.cj.jdbc.Driver. The old class name has been deprecated.
I am trying to create my first API using java httpServlet and netbeans which will be connected to a database on google cloud based its examples and documentations. I have not created the database, but I was given the necessary credentials and vars to create the connection. So I have downloaded the project from github, and when I tried to open it from netbeans there was some issues concerning dependencies ... So I resolved them, I replaced the credentials with their values and run the project; Unfortunately an error was thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. I made some searches but did not get any result... Could it be an error from this code ? an error from database security if it was invisible on cloud? Any help is more than appreciated.
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "<foo:foo:bar>";
String databaseName = "myDatabaseName ";
String username = "myUsername ";
String password = "<myPass>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
try{
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
/* try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select * from wf_accounts;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}*/
}catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
Update
Same error was thrown when I did this:
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
"",
"");
Any hints?
First you have to check whether the mysql server is running on.If you are Windows user you can simply
Go to Task Manager
Go to Services
then search for your Mysql server(eg:for my case its MYSQL56)
then you will see under the status column it says its not running
by right clicking and select start
If it's already running then you have to do as in mysql Documentation,
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem