Access to MySQL using Java Servlet? - mysql

The Solution:
I added this code
Class.forName("com.mysql.jdbc.Driver");
brfore
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
Thank you all for reply my question
====================
I have problem, I try to insert data into mysql db using servlet, but I couldn'y access to MySQL
Database name: test
Table name: test
I already added jdbc connector to the project library
I'm using JDK 1.7, NetBeans 7.3, MySQL 5.6, Tomcat 7.0, Connector/J 5.1.24
1- this is "form action" in sign_up.jsp page:
<form action="RegisterUser" method="post">
<td><input type="submit" value="Submit"></td>
</form>
2- this is RegisterUser.java servlet:
import java.io.IOException;
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 com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/RegisterUser"})
public class RegisterUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan3";
int phone = 123456;
String insert = "INSERT INTO test VALUES ('\" + name + \"', \" + phone + \")";
s.executeUpdate(insert);
s.close();
con.close();
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
3- the exception result:
HTTP Status 500 - Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
type Exception report
message Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.SecurityException: Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
RegisterUser.processRequest(RegisterUser.java:66)
RegisterUser.doPost(RegisterUser.java:173)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
4- But when I use same code but in java file "without servlet or web app" it's working correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan4";
int phone = 8985895;
String insert = "INSERT INTO test VALUES ('" + name + "', " + phone + ")";
s.executeUpdate(insert);
s.close();
con.close();
System.out.println("done");
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
}
so what is problem with servlet? Why the code works with java app. but it doesn't work with web app.?

You are getting Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
It means When you are running it from Web Application, JRE could not find Class in the Classpath.
If this code works in your Standalone it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest placing mysql-jdbc.jar at a physical location to /WEB-INF/lib directory of your project.
Alternatively, you can add Third party libraries like JDBC driver here using
Right Click Project Name--> Properties
from your NetBeans IDE
Then restarting Tomcat should work.
Second, you don't need
import com.mysql.jdbc.Driver;
in your Servlet.

David is right and i want to add, you can also install the driver by pasting the jar file in the the installation folder of java.
\Program Files\Java\jre7\lib\ext
Well i dont like mysql very much and always use Mssql with a windows server 2008. This is the code i use for that, i might be your answer since mysql connection works pretty much the same as sql.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName="+database+";user="+user+";password="+password);

First, you should put that into a persistance layer.
1) Ensure that your JDBC driver is in place. Copy it into your classpath, e.g. /WEB-INF/lib directory. Link: MySQL JDBC Driver Download Page
2) Check your connect string: jdbc:mysql://<server>:<port>/<database>, looks like the port is missing. Try jdbc:mysql://127.0.0.1:3306/test

Related

How to import MySQL using Gradle and connect into JavaFX

I'm using IntelliJ IDEA and JavaFX 10 for my practice learning. I want to connect MySQL and import it using Gradle.
I found multiple example in internet but I din't found any latest, most of the function is already depreciated and reading so much different example makes me confused.
You may want to read first the official documentation instead of reading multiple example.
I assume that you are beginner.
1.) First thing to do is to Download the MySQL Installer to intall the Server into your machine. Remember that things won't work without this.
During the installation you will need to set your Server PORT, root password or add a new user, just remember the Server PORT and root Password and leave things in default.
2.) Go to Maven Central. We need to import the MySQL Connector. In order to import the MySQL Connector into Gradle we need to get the correct group, name and version for it.
You notice that in Maven Central there are multiple selection on how you can import the jar into your project, this time we want to import it using Gradle,
so you have to choose the Gradle and copy the code: compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
NOTE - In order to avoid problems, just always choose and use the latest version of MySQL Installer and MySQL Connector, at the moment the latest version is 8.0.11.
3.) In IntelliJ IDEA, in order to import in Gradle, in your project there is build.gradle click it to open then paste the code you copied in dependencies.
it should look like:
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
}
4.) Create a class where you want to connect into MySQL, the below code is my example.
Main.Class
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args){
Connection conn = null;
String user = "whatEverUserNameYouSetup";
String password = "whatEverPasswordYouSetup";
String database = "whatEverTheNameOfYourDatabase";
int port = 3306; //default port, change it depending on your setup
try {
Class.forName("com.mysql.cj.jdbc.Driver").getConstructor().newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:" + port + "/" + database, user, password);
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
NOTE: The documentation is your friend.
UPDATE: If you run on error something like
Wed Dec 09 22:46:52 CET 2015 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
then you need to set useSSL to false, the code will be look like:
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Main {
public static void main(String[] args){
Connection conn = null;
Properties properties = new Properties(); //I use Properties to make things easer.
properties.setProperty("user", "root");
properties.setProperty("password", "YourPassword");
properties.setProperty("useSSL", "false"); //Set useSSL to false to solve the problem.
try {
Class.forName("com.mysql.cj.jdbc.Driver").getConstructor().newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306", properties);
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Servlet [duplicate]

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 5 years ago.
I am writing servlet to connect with mysql database using mysqlconnector java but it is giving error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
I have tried same with core java using the same driver it is connecting to mysql and query is also running but using servlet it is not working.
my code is for servlet is:
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 RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
String p = request.getParameter("password");
String e = request.getParameter("email");
String c = request.getParameter("course");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/phpmyadmin/saiiff","root", "");
PreparedStatement ps = conn
.prepareStatement("insert into eemeze values(?,?,?,?)");
ps.setString(1, n);
ps.setString(2, p);
ps.setString(3, e);
ps.setString(4, c);
int i = ps.executeUpdate();
if (i > 0)
out.print("You are successfully registered...");
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
Download the mysql jar from http://www.java2s.com/Code/JarDownload/com.mysql/com.mysql.jdbc_5.1.5.jar.zip
And Build on classpath

Unable to get connection to mysql database in netbeans java web application

I am new to web development to java. I am writing this basic java web application that is going to store customer information into a database. I use the MVC-2 architecture. My Jsp sends a request to a servlet that in turn tries instatiates a bean an inserts that object into a database.
When i try to connect to the database (in debugging mode) the connection variable returns empty. So data cannot be inserted.
This is the class that makes connections to the db
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package customer;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* #author
*/
public class DatabaseOperations implements Serializable
{
private static Connection connection;
public DatabaseOperations()
{
try
{
String username = "root";
String password = "root";
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection (url, username, password);
System.out.println("Database connection established");
}
catch(Exception e)
{
}
}
public static Connection getConnection()
{
return connection;
}
}
This is the method that adds a customer to the db
public void addCustomer(CustomerBean customer) throws SQLException {
DatabaseOperations db = new DatabaseOperations();
connection = DatabaseOperations.getConnection();
statement = connection.createStatement();
String query = "insert into customer (name, address, phone, email) "
+ "values (" + customer.name + ","
+ customer.address + ","
+ customer.phone + ","
+ customer.email + "," + ")";
statement.executeUpdate(query);
}
and finally this is the servlet where i call the method to add a customer
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package customer;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import customer.CustomerBean;
import javax.servlet.RequestDispatcher;
/**
*
* #author
*/
public class CustomerServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
CustomerBean customer = new CustomerBean();
try {
out.println("tests");
customer.setName(request.getParameter("name"));
customer.setEmail(request.getParameter("email"));
customer.setAddress(request.getParameter("address"));
customer.setPhone(request.getParameter("phone"));
/************** ADD CUSTOMER TO DB HERE***********************/
customer.addCustomer(customer);
request.setAttribute("cust", customer);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
catch (Exception e)
{
e.printStackTrace();
}
}
First, I'd like to point out that your code is open to SQL injection. Personally, I'm a fan of procedures, so I'll recommend that: you should create a procedure in mysql to insert a new record, and then provide that sproc with the arguments (name, address, etc).
As for the problem at hand: After your statement.executeUpdate line, try closing the connection. Also, extract the Class.forName to your main method. It should only be executed once. Also, remove the .newInstance() off of that once you have done so.
If all that doesn't work, extract the entire connection out to a globally accessible static variable and do not assign to it more than once. See if your program works then. If not, you have a separate problem.

How to configure tomcat to work with mysql in OpenShift?

I just discovered OpenShift and i love it! And i would like to try it with a tomcat app that communicates with mysql.I was able to install tomcat through this tutorial
and my tomcat server is up and running !I also installed mysql and phpmyadmin,but now i have to deploy my servlet in the tomcat server .My servlet communicates with mysql but i cant find where to insert the variables that Openshift give me !Does anyone have any idea?
Thnx in advandce Andi :)
OPENSHIFT VARIABLES ARE:
Root User :andi
RootPassword: andi
Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
MY SERVLET:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
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 com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String titulli = request.getParameter("titulli");
String ingredientet = request.getParameter("ingredientet");
String receta = request.getParameter("receta");
final String url = "jdbc:mysql://localhost/andi";
final String user = "andi";
final String password = "andi";
try {
// jdbc try
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(url, user,
password);
// insert values into the first table
PreparedStatement s = (PreparedStatement) con
.prepareStatement("INSERT INTO recetat(titulli,ingredientet,receta) VALUES (?,?,?)");
s.setString(1, titulli);
s.setString(2, ingredientet);
s.setString(3, receta);
s.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
PrintWriter out = response.getWriter();
out.println("Receta u ruajt me sukses ne server !");
System.out.println(titulli+ingredientet+receta);
}
}
like you can see i dont know where to insert the
Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
variable...
OpenShift puts the MySQL host and port as environment variables on exactly that name. In Java terms, they are available by
String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
Then, compose the JDBC URL as follows
String url = String.format("jdbc:mysql://%s:%s/andi", host, port);
The normal approach, however, is to create a connection pooled datasource in context.xml and obtain that by JNDI instead.
Somewhat related - you can now install tomcat directly (without following the DIY steps) but running
rhc app create <name> jbossews-1.0
JBoss EWS is a maintained and supported version of Tomcat from Red Hat - all the same bits. Also, starting next week the rhc client tools will support
rhc app create <name> tomcat6
To make it even simpler.

SQLException - Connection reset error

I am trying to establish a jdbc connection with SQL Server 2008 R2, using the SQLJDBC4 jar file and JDK 1.6. I am using Netbeans IDE and have added the SQLJDBC4 jar and added the path to the database in the 'databases' section in the services. The code is as below:
package connect2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connect2 {
public static void main(String[] args) throws SQLException {
Connection conn;
conn = null;
System.out.println("Done....");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection ("jdbc:sqlserver://172.17.39.13\\CRM:1433;databaseName=crm_xchanging","crm_xchanging","Welcome001");
System.out.println ("Database connection established");
}
catch (ClassNotFoundException e)
{
System.out.println (e);
}
catch (SQLException ex)
{
System.out.println(" error");
}
finally
{
if (conn != null)
{
try{
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM usertable");
System.out.println("User Name: " );
while (res.next()) {
String employeeName = res.getString("user_name");
System.out.println(employeeName);
}
conn.close();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex = ex.getNextException();
// For drivers that support chained exceptions
}}
}
}
}
}
This is the output I'm getting:
run:
Done....
Database connection established
SQLException information
Error msg: Connection reset
SQLSTATE: 08S01
Error code: 0
BUILD SUCCESSFUL (total time: 1 second)
I don't think there is any mistake in the code or the JDK. I have also tried to set the max no. of active connections for SQL Server as 0 (infinite). How do I solve this problem?
There is a known bug introduced in Java 6u29 that causes SSL failure specifically with SQL Server 2008 R2. An Atlassian Fisheye troubleshooting page suggests a fix was incomplete.
Oracle delivered a fix in 6u30, although for at least one affected
client not even Java 1.7 worked.
On my development team we have found this bug to impact Java 8 at as well. One of the recommendation in the Fisheye article is to disable CBC protection using a JVM flag and that has also worked for me for SSL Java 8 SSL with a SQL Server 2008 R2 connection.
-Djsse.enableCBCProtection=false
The other suggestion is to revert to Java 1.6.0_24.