This is the code of my index.jsp:
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="org.apache.tomcat.jdbc.pool.DataSource"%>
<%#page import="org.apache.tomcat.jdbc.pool.PoolProperties"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div id="query">
<%
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#localhost:1521:XE");
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("scott");
p.setPassword("tiger");
p.setMaxActive(100);
p.setInitialSize(10);
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
Connection con = null;
con = datasource.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select 777 from dual");
while (rs.next()) {
System.out.println(rs.getString(1));;
}
rs.close();
st.close();
%>
</div>
</body>
</html>
This is the error im getting for running that code:
I dont understand why this code runs for oracle:
<%
String dcn = "oracle.jdbc.OracleDriver";
Class.forName(dcn);
String serverName = "localhost";
String portNumber = "1521";
String sid = "orcl";
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + sid;
String username = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stm = conn.createStatement();
String query = "SELECT * from emp";
ResultSet data = stm.executeQuery(query);
while (data.next()) {
String number = data.getString("EMPNO");
String name = data.getString("ENAME");
%> <%=number%> <%=name%> <br> <%
}
%>
Dispite the fact that I imported the drivers properly. How should i do this in mysql ? Tried replacing driver but doesnt work either.
MYSQL Code:
<div id="query">
<%
String username = "j2ee";
String password = "j2ee123456";
String dbName = "testjava";
String dbHost = "localhost";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException msg) {
out.println("Error loading driver:" + msg.getMessage());
}
try {
String url = "jdbc:mysql://" + dbHost + ":3306/" + dbName;
Connection Conn = DriverManager.getConnection(url, username, password);
Statement Stmt = Conn.createStatement();
String query = "SELECT * FROM example_autoincrement";
ResultSet rs = Stmt.executeQuery(query);
while (rs.next()) {
int numExp = rs.getInt("id");
String nombre = rs.getString("data");
%> <%=numExp%> <%=nombre%> <%
}
} catch (SQLException e) {
String err1Msg = e.getMessage();
%>
<STRONG><EM> <%=err1Msg%> </EM></STRONG>
<%
}
%>
The error im getting on VPS
Error loading driver:com.mysql.jdbc.Driver No suitable driver found for jdbc:mysql://localhost:3306/testjava
However I dont get this error with XAMPP running same code...
Solved: after putting the mysql driver in the WEB-INF/lib folder had to restart tomcat.
Related
I am trying to update record in MySQL table. But when I execute it, it is not reflecting changes. No error or exceptions occurred. I tried with con.commit() and con.setAutoCommit(false) but no changes reflected. Only Home button is displayed on screen and even alerts in my program not displayed.
This is editnew.jsp
<tr>
<td></td>
<td>
<input type="hidden" value="update" name="update"/>
<input type="submit" value="Update" class="btn btn-primary"/>
</td>
</tr>
This is my editprocess.jsp code
<%#page import="java.io.File"%>
<%#page import="java.sql.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<title>editprocess jsp Page</title>
</head>
<body>
<%
String z_id = request.getParameter("zid");
String first_Name = request.getParameter("firstname");
String last_Name = request.getParameter("lastname");
String mail_i_d = request.getParameter("mailid");
String d_iv = request.getParameter("division");
String de_pt = request.getParameter("department");
...
String iss_uer = request.getParameter("issuer");
String sta_tus = request.getParameter("status");
String file_Name = "";
String folder_Name = "allfiles";
String pa_th = folder_Name + File.separator + file_Name;
Timestamp add_ed_date = new Timestamp(System.currentTimeMillis());
if(request.getParameter("update") != null){
Connection con = null;
PreparedStatement ps = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dmsqms","root","");
String sql = "update dmsfiles set firstname=?,lastname=?,mailid=?,division=?,department=?,costcentercode=?,document_number=?,document_name=?,document_type=?,document_category=?,document_classification=?,authorised_by=?,fromdate=?,todate=?,document_level=?,document_general=?,serial_number=?,revision_number=?,issuer=?,status=?,filename=?,path=?,added_date=? where document_name='"+doc_Name+"'";
ps = con.prepareStatement(sql);
// ps.setString(1,z_id);
ps.setString(1,first_Name);
ps.setString(2,last_Name);
ps.setString(3,mail_i_d);
ps.setString(4,d_iv);
ps.setString(5,de_pt);
ps.setString(6,cost_centercode);
ps.setString(7,doc_num);
ps.setString(8,doc_Name);
ps.setString(9,doc_Type);
ps.setString(10,doc_Category);
ps.setString(11,doc_classification);
ps.setString(12,authorised_by);
ps.setString(13,from_date);
ps.setString(14,to_date);
ps.setString(15,document_level);
ps.setString(16,document_general);
ps.setString(17,serial_number);
ps.setString(18,revision_number);
ps.setString(19,iss_uer);
ps.setString(20,sta_tus);
ps.setString(21,file_Name);
ps.setString(22,pa_th);
ps.setTimestamp(23, add_ed_date);
int i = ps.executeUpdate(sql);
con.commit();
if(i > 0)
{
out.println("alert('Record Updated Successfully');");
}
else
{
out.println("alert('There is a problem in updating Record.');");
}
}
catch(SQLException sql)
{
sql.printStackTrace();
}
}
%>
Home
</body>
</html>
im trying to create a matrix based on registers of a database named "foro", the problem is that im getting a nullPointerException i have tried everything, well here's the jsp code:
<%#page import="DB.MySqlConn"%>
<%#page import="java.sql.SQLException"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:useBean id="link" class="DB.MySqlConn"/>
<%#page session="true"%>
<%
String query="select * from consulta order by fecha";
String [][]pub=null;
pub=link.ConsultMat(query);
for(int i=pub.length-1;i>=0;i++){
out.println(pub[i][4]);
}
%>
and this is the class named "MySqlConn":
public class MySqlConn
{
public Statement stmt=null;
public ResultSet rs=null;
public Connection conn=null;
ResultSetMetaData rsmd =null;
boolean cont=true;
public MySqlConn()
{
cont=true;
try{
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost/foro?"
+ "user=root&password=MyPass";
conn = DriverManager.getConnection(connectionUrl);
}catch(SQLException e){
System.out.println("SQL Exception: "+e.toString());
cont=false;
}catch(ClassNotFoundException e){
System.out.println("Class Not Found Exception: "+e.toString());
cont=false;
}
}
public String[][] ConsultMat(String query){
int n=0,m=0;
int i,j;
String[][]datos=null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
if(stmt.execute(query)){
rs = stmt.getResultSet();
rsmd = rs.getMetaData();
rs.last();
n=rs.getRow();
rs.first();
m=rsmd.getColumnCount();
datos = new String[n][m];
for(i =0;i<n;i++){
for(j=0;j<m;j++){
try{
datos[i][j]=rs.getString(j + 1);
}catch(Exception e){}
}
try{
rs.next();
}catch(Exception e){}
}
}
}catch(SQLException e){
System.out.println("SQLException: "+e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("Error: " + e.getErrorCode());
}
return datos;
}
}
please help me !
Change:
for(int i=pub.length-1;i>=0;i++){
to:
for(int i=pub.length-1;i>=0;i--){
you are iterating in a wrong direction.
I am new to jsp.I have a table named employee now I want to insert image to datatase using a name as request parameter.The table already have name,age,id,phonenumber,email,password as fields.image is my new field I created now.When updating image field with new blob image it is not showing error but image is not inserting. Here's my try :
// My form to fileupload
<form name="frm" action="Image.jsp" method="post">
<center>Name:<input type="text" name="name"><br></center><br>
<center><br><br> <input type="submit" value="Submit"></center>
</form>
//(Image.jsp )My pgogram to get file from client and store in database
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="org.apache.commons.io.output.*"%>
<%# page import="org.apache.commons.fileupload.servlet.*"%>
<%# page import="org.apache.commons.fileupload.disk.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<html>
<body>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/praveen";
PreparedStatement pstatement = null;
FileInputStream inputStream = null;
int insertQuery = 0;
byte[] b = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");
String sql = "update employee set image=? where name=? ";
pstatement = connection.prepareStatement(sql);
pstatement.setString(2, request.getParameter("name"));
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
List items = sfu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
b = item.get();
}
}
pstatement.setBytes(1, b);
insertQuery = pstatement.executeUpdate();
pstatement.close();
connection.close();
%>
<input type="submit" value="Login">
</body>
</html>
<% # page import="java.io.*" %>
<% # page import="java.sql.*" %>
<% # page import="java.util.zip.* "%>
<%
String saveFile="";
String contentType=request.ContentType();
if((contentType != null) &&(contentType.indexOf("multipart/form-data")>=0))
{
DataInputStream in= new DataInputStream(request.getInputStream());
int formDataLength=request.getContentLength();
byte dataBytes[]= new byte[formDataLength];
int byteread=0;
int totalbyteread=0;
while(totalbyteread<formDataLength)
{
byteread=in.read(dataBytes,totalbyteread,formDataLength);
totalbyteread =byteread+1;
}
String file= new String(dataBytes);
saveFile=file.subString(file.indexOf("filename=\"")+10);
saveFile= saveFile.subString(0,saveFile.indexOf("\n"));
saveFile=saveFile.subString(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));
int lastIndex=contentType.lastIndexOf("=");
String boundry=contentType.subString(lastIndex+1,contentType.length());
int pos;
pos=file.indexOf("filename=\"");
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
int boundrylocation=file.indexOf(boundry,pos)-4;
int startpos=((file.subString(0,pos)).getBytes()).length;
int endpos=((file.subString(0,boundryloction)).getBytes()).length;
File ff= new File(saveFile);
FileOutputStream fileout= new FileOutputStram(ff);
fileout.write(dataBytes,startpos,(endpos-startpos));
fileout.flush();
fileout.close();
%>
<Br><table border="2"><tr><td><b>You have successfully upload the file:</b>
<%out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/praveen";
PreparedStatement pstatement = null;
FileInputStream inputStream = fis;
ResultSet rs=null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");
File f= new File(saveFile);
pstatement=connection.prepareStatement("insert into employee(name of image cloumn) values(?)");
pstatement.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = pstatement.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){e.printStackTrace();}
}
}
%>
i had written a jsp page with database connectivity getting the data from the database and printing it json format. And now i want that json data to be sent to the dojo data grid
Any help?
here is my jsp code
<%# page import="javax.security.auth.Refreshable"%>
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%# page import="org.json.simple.JSONObject"%>
<%# page import="org.json.simple.JSONArray"%>
<%#page import="java.util.LinkedList"%>
<%#page import="java.util.List"%>
<%
JSONObject responseObj = new JSONObject();
List<JSONObject> data = new LinkedList<JSONObject>();
try {
String dbms = "mysql";
String serverName = "localhost";
String portNumber = "3306";
String userName = "root";
String upassword = "";
String databaseName = "testind";
int datacount = 0;
String connectionURL = "jdbc:" + dbms + "://" + serverName
+ ":" + portNumber + "/" + databaseName;
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL,
userName, upassword);
System.out.println("connection::" + connection);
String strQuery = "select * from user";
System.out.println(strQuery);
PreparedStatement st = connection.prepareStatement(strQuery);
ResultSet rs = st.executeQuery();
while(rs.next())
{
datacount++;
JSONObject dataobject = new JSONObject();
dataobject.put("sl",(String.valueOf(datacount)));
dataobject.put("name",rs.getString(1));
dataobject.put("email",rs.getString(2));
dataobject.put("mobi",rs.getString(3));
dataobject.put("add",rs.getString(4));
data.add(dataobject);
System.out.println("name&email::"+rs.getString(1) +","+rs.getString(2));
}
responseObj.put("data",data);
PrintWriter writer = response.getWriter();
System.out.println("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" +responseObj+"}");
//writer.write("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" +responseObj+"}");
writer.write(" "+responseObj+"");
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println(e);
}`enter code here`
%>
here, i am getting the data from the database in the json format as following:
{"data":[{"sl":"1","email":"srinath#gma","name":"shivasrinat","mobi":"9849692921","add":"manikonda"},{"sl":"2","email":"srinath#gma","name":"shivasrinat","mobi":"9849692921","add":"manikonda"}]}
Remove data object in json
for example,
responseObj.put("data", data);
PrintWriter writer = response.getWriter();
System.out.println("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" + responseObj + "}");
writer.write("{\"identifier\":\"Id\",\"label\":\"Organisation\",\"items\":" + responseObj.remove("data") + "}");
//writer.write(" " + responseObj + "");
writer.flush();
writer.close();
i can successfully insert data into the table but when i try to get that data i get binary data only so how to get binary data from mysql into the String which they originally have.
Data_type is LONGBLOB.
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.io.File"%>
<%#page import="java.io.FileInputStream"%>
<%#page import="java.sql.PreparedStatement"%>
<%try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/beehivej_beehivejobs", "root", "root");
String fileName="C://1234.doc";
File file = new File(fileName);
FileInputStream fin = new FileInputStream(file);
PreparedStatement pre = conn.prepareStatement("insert into mytable( file, file_data) values ( ?, ?)");
pre.setString(1, fileName);
pre.setBinaryStream(2,fin,(int)file.length());
pre.executeUpdate();
System.out.println("Inserting Successfully!");
pre.close();
conn.close();
}
catch (Exception e){
System.out.println(e.getMessage());
}
%>