My IDE is Eclipse Indigo. I get this when I was trying to connect:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
And here is my code.
public class TPCH
{
public static void main(String[] args)
{
String userName = "tpch";
String password = "tpch";
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", userName);
connectionProps.put("password", password);
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e)
{
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/",
connectionProps);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("Error connecting to db");
}
}
}
I think JDBC is not imported. I tried to import it by
preference -> java -> build path -> user library -> add jars
But I still got that exception.
That's not how you add JARs to the classpath in Eclipse.
You have to right-click on your project, select Java Build Path > Libraries and add a JAR file. For MySQL, you'd need the MySQL Connector J.
Related
I'm newbie at Java netbeans , I am trying to load mysql driver, but my Netbeans IDE don't show libary folder in my Project.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Its My First Project");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mychakki", "root", "password");
System.out.println("Connection Established ");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Exception :" +e.getMessage());
}
I wanted to connect DB to Java application in Intellij.
I set the classpath correctly, so that javac from cmd is working correct.
I have also downloaded all the jar files needed as a libary, but I still get java.sql.SQLException: No suitable driver found for jdbc:derby
What can be the problem?
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";
try (
Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
)
{
// ...
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
You can try if org.apache.derby.jdbc.EmbeddedDriver works. And it seems your connection url is wrong.
final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
Connection connection = null;
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager.getConnection(DATABASE_URL );
}
catch (Exception e)
{
e.printStackTrace();
}
I've trouble with connection to database MySQL. I wrote a console project with databese and I had a class ConnectionManager here. Now I'm starting writing site. I want connect database ang just copy my working classConnectionManager into new dynamic project. But this class return NULL instead of connection. Maybe you know where is problem.
Thank you in advance!
Connector is added. NullPointer exception was called by Connection conn = ConnectionManager.getConnection();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private static String jdbcUrl = "jdbc:mysql://localhost:3306/registration";
private static String user = "root";
private static String password = "root";
private static Connection connection = null;
public static Connection getConnection()
{
if (connection == null)
{
initializeConnection();
}
return connection;
}
private static void initializeConnection()
{
Connection conn;
try {
conn = DriverManager.getConnection(jdbcUrl,user,password);
connection = conn;// doesn't execute and I don't know why
} catch (SQLException e) {
e.printStackTrace();
}
}}
Using: Connection conn = ConnectionManager.getConnection();
Try making the constructor and add your code in that. I'm doing exact same thing and its working. Like this:-
public Connection() {
// TODO Auto-generated constructor stub
try {
if (connection == null)
{
initializeConnection();
}
return connection;
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Probably more than one reason
1- check your user permission
GRANT [type of permission] ON [database name].[table name] TO ‘[username]’#'localhost’;
GRANT ALL PRIVILEGES ON * . * TO 'root'#'localhost';
2- check your jdbc url and its port. Make sure 3306 port is avaible to using mysql
jdbc:mysql://localhost:3306/registration
3- check your jar file
Download .jar file(mysql-connector-java-5.1.37-bin.jar) and move it to libs folder
Right click your project > properties > Libraries > ADD jar/Folder Select your jar file in that folder.
Test your connection
String dbUrl= "jdbc:mysql://localhost:3306/javabase";
String username = "root";
String password = "root";
try (Connection connection = DriverManager.getConnection(dbUrl, username, password)) {
System.out.println("Connected to DB!");
} catch (SQLException e) {
throw new IllegalStateException("Error: ", e);
}
4- check your user password.
if you not sure change your password.
SET PASSWORD FOR 'root'#'localhost' = PASSWORD('root');
I’m trying to connect a Java program with MS SQL SERVER 2012 but Java throws the exception: java.lang.ClassNotFoundException.
I understand that the problem often is a result of that the CLASSPATH is not set up correctly for the driver. I have followed the directions from Oracle to add a CLASSPATH, but I still get the same exception. When I type “echo %CLASSPATH%" in the command prompt I get a correct response. What have I missed?
Code:
import java.sql.*;
public class JDBCTest {
public static void main(String[ ] args) throws SQLException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch(Exception e) {
System.out.println("Can't find database driver: " + e);
}
}
}
The runtime environment for your application may not contain the appropriate jar file.
The path that you have checked is only for your console environment. The application classpath is different from this.
Try this
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=YourDBName;user=UserName;Password=YourPassword"
// 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);
String SQL = "";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
....
}
}
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) {}
}
}
}
make sure that you download the driver jar file and put it at the right place
If Class.forName fails it is a problem of classpath.
try this code to check your classpath:
String classPath = System.getProperty("java.class.path");
String userDir = System.getProperty("user.dir");
System.out.println("Working Directory:");
System.out.println("\t"+userDir);
System.out.println("Classpath:");
String[] paths = classPath.split(";");
for (String path : paths) {
File pathFile = new File(path);
String check = pathFile.exists()?"OK ":"NOT-FOUND ";
System.out.println("\t"+check+path);
}
First of all download sqljdbc4.jar from here
Put this .jar in Your /WEB-INF/lib folder. (Check if this file appears from your eclipse's lib if not then Refresh Your Project)
And then run Your Project.
My servlet function looks like these:
CODE:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
String userName;
String passwd;
Connection conn = null;
userName = (String)request.getParameter("userName");
passwd = (String)request.getParameter("password");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //Or any other driver
}
catch( Exception x ){
System.out.println( "Couldn’t load drivers!" );
}
try
{
conn = DriverManager.getConnection("jdbc:sqlserver://192.168.0.123:1433;databaseName=test","sample","sample");
}
catch( Exception x)
{
System.out.println("Couldnot get connection");
}
}
the output goes to two catch statements.How to overcome this?
Reply as soon as possible?
Are you running this from within Eclipse? It looks like you need to add a the driver JAR file to your dependencies. You can do this from the project build path settings within Eclipse (right-click the project, select Build Path -> Configure Build Path). Then under the 'Libraries' tab you can add any jars needed, such as the SQL server driver JAR file.
If you are deploying this to a Servlet container, it looks like the JAR file is missing from the WEB-INF/lib folder. Copy it here and you should find it works.
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://192.168.0.123:1433;databaseName=test", "sample", "sample");
} catch (ClassNotFoundException e) {
System.out.println( "Couldn’t load drivers!" );
} catch (SQLException e) {
System.out.println("Couldnot get connection");
}
or
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://192.168.0.123:1433;databaseName=test", "sample", "sample");
} catch (Exception e) {
if (e instanceof ClassNotFoundException) {
System.out.println( "Couldn’t load drivers!" );
} else {
if (e instanceof SQLException) {
System.out.println("Couldnot get connection");
}
}
}