Class Notfound exception in sqlserver connection in eclipse - java

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");
}
}
}

Related

Connect derby DB to Java

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();
}

JDBC - java can't see installed drivers

I have a problem with JDBC drivers. I can't connect with my SQL Server database. Following code for test:
public class Test {
public static void main(String[] args) {
Connection con = null;
String conUrl = "jdbc:sqlserver://localhost:1433; databaseName=mydb; user=root; password=psswd;";
try {
con = DriverManager.getConnection(conUrl);
System.out.println("OK");
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
}}
When i try run this code i still getting error:
java.sql.sqlexception no suitable driver found for (..)
I have added path to sqljdbc4.jar to classpath variable and enu\auth\x64 localization to Path variable. I'm working on JRE 1.8, SQL Server 2014 and Windows 7.
It's because you haven't loaded the driver. Just modify your existing code
try {
//this will load the driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(conUrl);
System.out.println("OK");
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}

servlet page shows blank when accessed later

I have a strange issue with servlet page. I have simple web application which contains just a servlet.I deployed it in Tomcat 7. When user enters url, the servlet should get directly executed, get the data from the database and print the output. But it shows blank page after some time. When I undeploy and deploy, it shows data. After some time when I access the page, it shows blank page. Then again when I redeploy, it shows data. Can someone please let me know how to resolve this? I have no clue why it happens. Below is my code.
I am using mysql database.mysql-connector-java-5.1.29-bin.jar added in lib folder and added to buildpath.
public class Homeservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String mysqldblink = "************";
static final String mysqlUsername = "username";
static final String mysqlPassword = "pw";
Connection connection =null;
Statement stmt = null;
/**
* #see HttpServlet#HttpServlet()
*/
public Homeservlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(mysqldblink,
mysqlUsername, mysqlPassword);
stmt = connection.createStatement();
}
catch(Exception E)
{
E.printStackTrace();
}
}
#Override
public void service(ServletRequest request, ServletResponse response)
{
PrintWriter pw = null;
try {
String query = "querytogetdata";
pw = response.getWriter();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
pw.println(rs.getString(1));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}finally{
try{
pw.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void destroy( ) {
// Close the connection
try {
if (connection != null)
connection.close( );
if(stmt != null)
stmt.close();
} catch (SQLException ignore) { }
}
}

JDBC SQL Server Exception

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.

I'm trying to connect mysql through JDBC on mac osx

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.

Categories