I tested that my Java program correctly retrieve data from MySQL. However, the problem is between Java and JSP. The JSP page can't retrieve data from the java program.
Please help me guys.
It gives the output as null:
null
null
.
.
.
hai
My jsp page:
<%@ page import="com.zoo.MySQLAccess"%>
<html>
<head>
</head>
<body>
<%
MySQLAccess x= new MySQLAccess();
String[] arr =x.getRows();
out.print("1" +arr[0]);
%>
<% for(String str:arr) { %>
<div style="height: 100px">
<% out.print(str); %>
</div>
<% } %>
<h1>hai</h1>
</body>
</html>
My java page is:
package com.zoo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class MySQLAccess {
public String[] getRows() {
String[] a = new String[100];
try {
// Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/sankar?"
+ "user=root&password=9788129325");
Statement statement = connection.createStatement();
ResultSet resultSet = statement
.executeQuery("SELECT * FROM sankar.datas");
int i = 0;
while (resultSet.next()) {
a[i] = resultSet.getString("name");
i++;
}
}
catch (Exception e) {
e.printStackTrace();
}
return a;
}
}
Since no elements are recorded, you have either one of two problems. You're not connecting to your database, or you're not querying your table correctly.
Check that you can connect to the "sankar" database on localhost, port 3306 as root with password 9788129325 using the command-line mysql client.
If that works, then check in mysql that you have a "datas" table in this sankar database. You don't really need to have "sankar.datas". You can just have "select * from datas".
If you can query the table, make sure it has a "name" column.
If it has a name column, make sure there is at least 1 row in this column.
If it has one row, make sure the "name" for that row is not null.
If this is the case, then your error is probably that you're loading your driver incorrectly. First off, you hopefully have the mysql-connector-java-<some version>-bin.jar in your application's classpath? Perhaps in your webapp's "lib" directory? Also, I assume that Class.forName that you commented out is somewhere else in the code? If not, you need that. Also, you can do it like this:
Class.forName("com.mysql.jdbc.Driver").newInstance();
The newInstance is a "workaround" for some Java implementations. Maybe yours needs that.
Anyway, again, the stack trace on your Java server is likely printing to the console, and should give you a better idea of what's going wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With