Error : No suitable driver found for database on AWS RDS - java

My code is as below, I have a MySQL DB on AWS RDS. I have also already included the mysql-connector-java-5.1.31-bin.jar in my build path.
My code is as below :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.sql.*"%>
<%# page import="java.util.Scanner "%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Customer to Online Mall</title>
</head>
<body>
<%
final String host = "jdbc:mysql://mySqlPath/ShopSystem";
final String uName = "myusername";
final String uPass = "mypassword";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
//#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String Cust_address, Cust_email, Cust_contact;
Connection con = DriverManager.getConnection( host, uName, uPass );
//View all shops
Statement stmt5 = con.createStatement();
ResultSet rs2 = stmt5.executeQuery("SELECT * FROM ShopSystem.Shop");
while(rs2.next())
{
System.out.print("s_id = "+rs2.getInt(1)+"\t");
System.out.print("s_name = "+rs2.getString(4)+"\t");
System.out.print("s_location = "+rs2.getString(3)+"\t");
System.out.println();
}
sc.close();
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
%>
</body>
</html>
I am getting the following error :
Aug 01, 2014 5:31:46 PM org.apache.jasper.compiler.Compiler removeGeneratedFiles
WARNING: Failed to delete generated Java file [C:\Users\Documents\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\local host\ShopSystem-AWSJavaWebProject\org\apache\jsp\WelcomeCustomer_jsp.java]
No suitable driver found for jdbc:mysql://mySqlPath/ShopSystem
Please help.
Thank you in advance.

Your this line seems to be incorrect.
final String host = "jdbc:mysql://mySqlPath/ShopSystem";
It should be something like this :
jdbc:mysql://localhost/ShopSystem
or
jdbc:mysql://{YOUR_IP}/ShopSystem // e.g. "jdbc:mysql://192.168.15.102/ShopSystem"

Related

My jsp code doesn't insert data in database

I am working on a JSP code and want to connect my page with mysql database and to insert name and email in database but it couldn't , I want to know why
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*, java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP handle Page</title>
</head>
<body>
<%
String first_name = request.getParameter("user");
String email = request.getParameter("email");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into info (name,email) values ('"+first_name+"','"+email+"')");
if(i!=0)
{
System.out.println("Data inserted");
}
else
{System.out.println("no");}
}
catch (Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>

How to display Java Multi threading output in jsp file

I have a Java Program which contains my own thread (start() and run() methods). Code is shown below :
public class MyClass
{
public void threadStart()
{
Threadone t1 = new Threadone();
t1.start();
}
}
class Threadone extends Thread
{
public void run()
{
String url = "jdbc:mysql://localhost:3306";
String user= "root";
String pwd = "root#123";
String qry = "SELECT Country FROM test.abuse WHERE Priority='High'";
Connection conn = null;
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pwd);
ResultSet rs = conn.prepareStatement(qry).executeQuery();
while(rs.next())
{
System.out.println(rs.getString("Country"));
}
}
catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
JSP File:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
MyClass my = new MyClass();
my.threadStart();
%>
</body>
</html>
As of now I am displaying the result in java console. But my task is to display the result in jsp file, Is it possible? If possible how to print the data in webpage using jsp file?
Create a shared collection like map or list .The background thread will populate into the shared collection.And through AJAX or other mechanism fetch from the shared collection.Consider thread safety as it required multiple thread will access the collection while background thread is processing.

Java not connecting to database

I'm trying to get my java code to connect to the database. I swear it was connecting a few hours ago and suddenly it's not. I have reinstalled, restarted xampp, eclipse my laptop. I even uninstalled and reinstalled mysql.
Here's my .java file:
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class Connect_db {
// private static final String url = "jdbc:mysql://localhost:3306/sjsu";
// private static final String user = "root";
// private static final String password = "";
//
// public static void main(String[] args) throws Exception {
// java.sql.Connection con = null;
// try {
// Class.forName("com.mysql.jdbc.Driver");
// con = DriverManager.getConnection(url, user, password);
// // commented since doesn't exists in Java 6
// // System.out.println(con.getSchema());
// System.out.println(con.getCatalog());
// } finally {
// con.close();
// }
// }
private static MysqlDataSource ds = null;
public static MysqlDataSource getDataSource(String db_name) {
if (ds == null) {
// db variables set here
getDataSource("jdbc:mysql://localhost:3306", "root", "", 3306);
}
ds.setDatabaseName(db_name);
return ds;
}
private static void getDataSource(String db_url, String db_user, String db_password, int db_port) {
try {
ds = new MysqlDataSource();
ds.setServerName(db_url);
ds.setUser(db_user);
ds.setPassword(db_password);
ds.setPort(db_port);
} catch (Exception e) {
System.out.println("MysqlDataSource err: " + e.getMessage());
e.printStackTrace();
}
}
}
My .jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>atozknowledge.com demo Regjsp</title>
</head>
<body>
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String user=request.getParameter("userid");
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = Connect_db.getDataSource("sjsu").getConnection();
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values ('"+user+"','"+pwd+"','"+fname+"', '"+lname+"','"+email+"')");
out.println("Registered");
%>
Home
</body>
</html>
My html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>atozknowledge.com demo Registration</title>
</head>
<body>
<form action="reg.jsp" method="post">
User name :<input type="text" name="userid" /><br/><br/>
password :<input type="password" name="pwd" /><br/><br/>
First name :<input type="text" name="fname" /><br/><br/>
Last name :<input type="text" name="lname" /><br/><br/>
Email :<input type="text" name="email" /><br/><br/>
<br/><br/>
<input type="submit" />
</form>
</body>
</html>
The error
It used to be able to put the userid, pwd, ... etc in my database and now it can't.
As the error states, it cannot find the class Connect_db. You need to add an explicit import for Connect_db to your JSP, that is add:
<%# page import ="package.of.Connect_db" %>
Querying directly from JSP is a poor choice, your should separate getting the data from displaying the data.
Tomcat also provides support for creating and registering data sources, use that instead of rolling your own. Especially, as MysqlDataSource doesn't provide connection pooling.
And finally, concatenating values into your query string is unsafe, especially with user provided input, as it leaves you open to SQL injection. Instead you should use a prepared statement with parameters. Please take a look at Using Prepared Statements in the JDBC tutorial.
I recommend you instead of giving the my.jsp inn the from action it is better to use a servlet. Maybe it can solve your. Create a new servlet and write your code inside of post method.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver (jar file already linked and placed in WEB-INF/lib)

The solutions I found for this error were "add the jar file via build path" and "put the jar file containing the driver in WEB-INF/lib" (and similar formulations) but I already tried the two of them.
Back to my problem. Here is my Code:
jsp-file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="db.DBAccess" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="dba" class="db.DBAccess"></jsp:useBean>
<jsp:setProperty name="dba" property="selection" value="s" />
</body>
</html>
javabean
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBAccess {
public DBAccess() {
}
private String selection = "";
public void setSelection(String s) {
final String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String user = "user1";
String pswd = "user1pswd";
Connection con = null;
Statement stmt = null;
try {
// initialize connection
Class.forName(driver);
con = DriverManager.getConnection(url, user, pswd);
stmt = con.createStatement();
// execute select
ResultSet results = stmt.executeQuery("SELECT * FROM t");
results.next();
selection = results.getString(1);
// close connection
stmt.close();
con.close();
} catch (ClassNotFoundException cnfe) {
System.out.println(cnfe.toString());
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
The content of t is one column with the label "string" and the content "hello world"
Why am I getting this exception even though I linked the jar file correctly?
Did you insert your jar file to lib folder of Webinf?

How to retrieve image from mysql db and show it inside <td> and <img> tag in HTML?

How to retrieve image from mysql db and show it inside tag in HTML and that img tag should be placed inside ? Here s my code:
It displays only the image . Its not showing any content other than image.
Thanks in advance.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
%>
<table border='1'>
<tr>
<td>Name:</td><td>
</td>My Name</td>
</tr>
<tr>
<td>Image:</td>
<td width=10px;>
<%
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
out.println("Retrieved Successfully!");
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</td></tr>
</table>
</body>
</html>
Images are loaded as separate requests to the request that loaded the html. As such you need to:
establish a URL encoding scheme that you use when specifying the src of the img element.
map a servlet (or similar) to that URL. The servlet loads the image based on the parameters of the URL returning that image in its response.
I found out.
r.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table border=2>
<tr><th>DISPLAYING IMAGE</th></tr>
<tr><td>hi</td></tr>
<tr><td>
<img src="retrieve.jsp" width=130 height=130>
</td></tr>
</table>
</body>
</html>
retrieve.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</body>
</html>

Categories

Resources