After updating the connection details to MariaDB, system throws ClassNotFoundException - java

I was advised by my web hosting company to change the 'mysql jdbc connection' details to 'mariadb' as per below in the getDBConnection().
I have downloaded the MariaDB jar [mariadb-java-client-1.7.4.jar] compatible for JDK 1.7 & added jar to the project.
Removed the existing MySQL jar [mysql-connector-java-5.1.40-bin.jar] to avoid any conflict. Clean and build the solution and restarted the tomcat server. While submitting the data system still throws below error. Also while debugging at this point, I am receiving null here connection = SoccerUtils.getDBConnection(); preparedStatement1 = connection.prepareStatement("insert into mydatabase.registeruser values(default,?,?,?,?,?,?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
Any idea Why this is still throwing ClassNotFoundException: com.mysql.jdbc.Driver ?
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Oct 15, 2018 10:53:57 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [RegisterServlet] in context with path [/MyFirstJavaTest] threw exception
java.lang.NullPointerException
at com.myfirstjavatest.pkg.RegisterServlet.addPlayer(RegisterServlet.java:134)
at com.myfirstjavatest.pkg.RegisterServlet.doPost(RegisterServlet.java:110)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
//Code below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public static Connection getDBConnection() {
String url = "jdbc:mariadb://localhost:3307/";
String dbName = "mydatabase";
String driver = "org.mariadb.jdbc.Driver";
String userName = "root";
String password = "mypassword";
Connection conn = null;
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
} catch (Exception e) {
System.out.println(e);
} finally {
}
return conn;
}

Related

Connect to SQL server from Java

I'm trying to connect from SSMS(SQL Server Management Studio) to Eclipse(Java), but I keep getting this error message:
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host localhost, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.getInstancePort(SQLServerConnection.java:6132)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.primaryPermissionCheck(SQLServerConnection.java:2609)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2346)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2213)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1276)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:861)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:16)
The code I do have is:
import java.sql.DriverManager;
import java.sql.SQLException;
//import com.sun.jdi.connect.spi.Connection;
public class JavaConnect2SQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=students"; // This is where I think the error is
String user = "sa";
String password = "123";
try {
java.sql.Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Succesfully connected to Microsoft SQL Server");
}catch (SQLException e) {
System.out.println("Oops! There was an error: ");
e.printStackTrace();
}
}
}
I think the problem is in the connection URL, but I don't know the host name/instance name. If you can tell me how to get my host name/instance name, that would be appreciated. But if the problem is something else, please tell me!
Edit: I have changed the code, and I'm now getting a different. Here is the new code:
package net.codejava.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JavaConnect2SQL {
public static void main(String[] args) {
// Create a variable for the connection string.
String url = " jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students";
String user= "sa";
String password = "123";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connection succesful!");
}
// Handle any errors that may have occurred.
catch (SQLException e) {
System.out.println("Here is your error message: ");
e.printStackTrace();
}
}
}
The new error message is this:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:40)
I think the problem is that I installed the wrong version of JDBC Driver. My JRE version is 12.0.1. What is the correct JDBC Driver to install.
You can check in SQL server configuration manager and Microsoft SQL server management studio. The state must be running in server configuration manager and you can try to connect your database in Microsoft SQL server management with your password.
if you connect successfully then there is another problem but it looks like the database is stopped.

Connecting to SQL Server 2014 from Android Studio

I have a problem connecting to SQL-server database through from my android project. I have added sqljdbc41.jar file to my /app/libs directory and I have added it to dependencies in my android studio project.
I use following code:
package com.konrad.rezerwacje1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Database_Console {
public static void openConnection(){
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"‌​);
String url = "jbdc:sqlserver://127.0.0.1:1433;databaseName=my_db";
Connection con = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
openConnection();
}
}
yet i still get this error
java.sql.SQLException: No suitable driver found for jbdc:sqlserver://127.0.0.1:1433;databaseName=my_db
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
Instead of this :
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"‌​);
String url = "jbdc:sqlserver://127.0.0.1:1433;databaseName=my_db";
You have to use this :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=my_db";
Connection con = DriverManager.getConnection(url, "username", "password");
Note the different classname, and the fact that prefix jbdc in the URL has been changed to jdbc.
If it is not a requirement to go with sqljdbc41.jar, then you might consider using the jtds driver for your requirement to connect to SQL Server 2014 with Android Studio. There are tons of articles that can help you start with this set of technologies.
For a primer, here are the details:
Download the JTDS driver from here
Then import this jar into your Android Studio, eg: jtds-1.2.5.jar
Use the following details in your code:
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/DATABASE;user=sa;password=p#ssw0rd");

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver during Dynamic Web Project creation in java

I am designing a registration page using MVC design pattern. I have made a class file which will input the parameters into the database using sql commands but i am getting
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Here is the code
package src.service;
import java.sql.*;
public class RegisterService {
public void addToDatabase(String name, String id, String email, String password){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
// Create a statement
Statement myStatement = myConn.createStatement();
String sql = "insert into userid values(" + id + ", '" + name + "', '" + email + "', '" + password + "')";
myStatement.executeUpdate(sql);
}
catch (Exception e){
e.printStackTrace();
}
}
}
I have imported the driver in my lib folder of the project, imported it in build path, imported it in tomcat server in the folder tomcatv7>lib by creating a lib folder. Still it is showing the same error. Kindly help.
You need to setup the DB Connection in server.xml
follow this tutorial :
http://examples.javacodegeeks.com/core-java/mysql-connector-for-java-how-to-install-in-eclipse-and-tomcat/
and
https://www.mulesoft.com/tcat/tomcat-mysql
as well as you need to download MySQL Connector from:
http://dev.mysql.com/downloads/connector/j/
and copy the jar file to "C:\tomcat7\lib"
You should add MYSQL JDBC LIBRARY to your project
and also import
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
This worked for me---
This solution is only for Dynamic web projects.
Steps--
1)Create a Dynamic Web project
2)I added the "mysql-connector-java-5.1.48-bin" jar in WebContent/WEB-INF/lib folder.
2) Create a tomcat server
3)inside src create a demo servlet--
package com.luv2code.testdb;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
/**
* Servlet implementation class TestDbServlet
*/
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// setup connection variables
String user = "springstudent";
String pass = "springstudent";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
4)Just right click and run as run on server select ur tomact server
Remember before all these you need to create ur db schema,
here i have used mysql workbench.
Mysql part is not covered in this answer.
If this does not work, try adding the msql connector jar inside tomcat/lib folder

Openshift - No suitable driver found for jdbc:mysql

I am new to Java and Servlet Programming. I am trying to host a simple application which is working successfully in localhost. but when i host it to Openshift, it says No suitable driver found for jdbc:mysql://127.12.204.2:3306/shifar .
All i want to do is to save a string into the database.
Here is my code
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String
HOST = System.getenv("OPENSHIFT_MYSQL_DB_HOST"),
PORT = System.getenv("OPENSHIFT_MYSQL_DB_PORT"),
USERNAME = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME"),
PASSWORD = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD"),
DB_NAME = "shifar";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("userName");
PrintWriter pw = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
pw.println("Error while loading driver: "+e.getMessage());
}
try {
String url = "jdbc:mysql://" + HOST + ":" + PORT +
"/" + DB_NAME;
Connection con = DriverManager.getConnection(url, USERNAME, PASSWORD);
PreparedStatement prep = con.prepareStatement("INSERT INTO names (name) VALUE (?)");
prep.setString(1, name);
int rc = prep.executeUpdate();
pw.println("Name saved !:"+name+" # "+ rc);
} catch (SQLException e) {
pw.println("Error while connecting: "+e.getMessage());
}
}
}
I can't figure out the error :(. The deployment of the application is done through Git as .WAR
Live Preview - (Enter something in the edittext and submit)
Your servlet container needs access to the jar file its way. For instance Tomcat might want something like mysql-connector-java-5.1.35-bin.jar
in the web-inf folder under the application. You need to focus on your classpath and the setup of your servlet container, regardless of what that is.
If you need further assistance hang a question under this with more details.

JBDC and Phpmyadmin / MySQL not connecting

Could someone explain to me where I'm going wrong with the following code:
package newdbtet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewDBTet {
public static void main(String[] args) throws InstantiationException, SQLException, IllegalAccessException {
try {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "evidence_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Connected to the database");
conn.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewDBTet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Exception error:
Jul 16, 2012 2:59:24 PM newdbtet.NewDBTet main
SEVERE: null
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Does this mean that I haven't installed the driver / library correctly? Sorry - not the best with Java.
download the MySQL Driver for Eclipse/Java then you should get a .jar driver. then right click on your class and go to build path. finally add the external library to your project, that should solve your problem.
Add the JDBC driver .jar into the class path with a -cp command, i.e. - java -cp MysqlDriver.jar; MyProgram or add the .jar into the build path in your IDE.

Categories

Resources