Is it possible to have AJAX output to html, rather than plain-text?
I have a file that pulls a class result from an SQL database. The database connection works, and it prints, but rather than printing the table format I desire, it simply prints the table elements as text on the page instead.
public class hw11
{
int crn;
String output = "temp";
public String getOfferings(int crn)
{
this.crn = crn;
//DB Connection
String url = "jdbc:odbc:registrar";
Connection con;
PreparedStatement stmt;
String query;
query = "SELECT * FROM offerings WHERE crn = " + crn +";";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try
{
con = DriverManager.getConnection(url, "", "");
stmt = con.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
output = "<table border='1'><tr>";
output+= "<th>CRN</th><th>Course</th><th>Section</th><th>Dates</th><th>Times</th><th>Instructor</th><th>Room</th><th>Max Enrolled</th><th>Current Enrolled</th></tr>";
while (rs.next())
{
String course = rs.getString("COURSE");
String section = rs.getString("SECTION");
String dates = rs.getString("DATES");
String times = rs.getString("TIMES");
String instructor = rs.getString("INSTRUCTOR");
String room = rs.getString("ROOM");
int enrollmax = rs.getInt("ENROLLMAX");
int enrollcur = rs.getInt("ENROLLCURRENT");
output += "<tr>";
output += "<td>"+crn+"</td><td>";
output += "<td>"+course+"</td><td>";
output += "<td>"+section+"</td><td>";
output += "<td>"+dates+"</td><td>";
output += "<td>"+times+"</td><td>";
output += "<td>"+instructor+"</td><td>";
output += "<td>"+room+"</td><td>";
output += "<td>"+enrollmax+"</td><td>";
output += "<td>"+enrollcur+"</td><td>";
output += "</tr>";
}
output += "</table>";
stmt.close();
con.close();
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
}
//Output
return output;
}
}
HTML Page:
<p>
Get Course Offerings
<br/><br/>
Course CRN: <input type="text" id="theCrn"/>
<input value="Send" type="button" onclick="update()"/>
<br/>Reply:<br/>
<span id="theReply"></span>
</p>
Yes, you can return anything in response to an ajax call.
Just make sure you append it properly to the page.
Related
I want to display values from database in many lines using jLabel. I tried using the html trick but I don't know how to apply it here in my code. I just get errors. Maybe I'm doing it the wrong way. Haha.
try{
//display doctor's name by selected classification
String url = "jdbc:mysql://localhost/sched";
Connection conn = DriverManager.getConnection(url,"root","");
Statement stmt = conn.createStatement();
String classification = comboClass.getSelectedItem().toString();
String sqlSelect= "select * from doctorsched where class = '"+classification+"'";
ResultSet rs = stmt.executeQuery(sqlSelect);
String finalText ="";
while(rs.next()){
String docsName= rs.getString("docName");
String room = rs.getString("room");
String days = rs.getString("day");
String from = rs.getString("timefrom");
String to = rs.getString("timeto");
finalText += docsName+" (room "+room+", "+days+", "+from+"-"+to+") \\n";
// i want to display values from database in many lines but using jLabel
}
jLabel10.setText(finalText);
} catch (Exception ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
Something like this should be my output
doc riza (room 104, Every Thursday, 10:30AM-10:00AM)
doc j (room 101, null, 10:30AM-11:30AM)
doc lea (room 102, Every Saturday, 10:30AM-4:30PM)
frida (room 101, null, 8:00AM-9:30AM)
Please help me out :(
The '\n' works in jTextArea but not in jLabel. I also tried '\n' in label, but doesn't work, too.
Okay so I tried this one
finalText += "<html>"+docsName+" (room "+room+", "+days+", "+from+"-"+to+")<br></html>";
But this code only display one line. The first row in my database. I need to display all of the rows.
Now, this next code shows it all, but the next line still doesn't work.
while(rs.next()){
String docsName= rs.getString("docName");
String room = rs.getString("room");
String days = rs.getString("day");
String from = rs.getString("timefrom");
String to = rs.getString("timeto");
finalText += docsName+" (room "+room+", "+days+", "+from+"-"+to+")\n";
}
jLabel10.setText("<html>"+finalText+"<br></html>");
}
Whyyy
use a code like this
String finalText = "";
for (int i = 0; i < 10; i++) {
finalText += "line:" + i;
finalText += "<br>";
}
label.setText("<html>" + finalText + "</html>");
try{
//display doctor's name by selected classification
String url = "jdbc:mysql://localhost/sched";
Connection conn = DriverManager.getConnection(url,"root","");
Statement stmt = conn.createStatement();
String classification = comboClass.getSelectedItem().toString();
String sqlSelect= "select * from doctorsched where class = '"+classification+"'";
ResultSet rs = stmt.executeQuery(sqlSelect);
String finalText ="";
while(rs.next()){
String docsName= rs.getString("docName");
String room = rs.getString("room");
String days = rs.getString("day");
String from = rs.getString("timefrom");
String to = rs.getString("timeto");
finalText += (docsName+" (room "+room+", "+days+", "+from+"-"+to+")\n") ;
finalText += "<br>";
}
jLabel10.setText("<html>" + finalText + "</html>");
} catch (Exception ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
I want to get my ItemName columns value to one String separate from commas.
I tried like this.but its not working
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '"+invoicenum+"' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
while (rs.next()) {
String em = rs.getString("ItemName");
description = em.replace("\n", ",");
System.out.println(description);
}
You should change to this, if you want to do the concatenation in java:
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
while (rs.next()) {
description += rs.getString("ItemName") + ",";
}
description = description.substring(0, description.length() - 1);
//System.out.println(description);
}
If you want to concatenate in query then you could search for GROUP_CONCAT() function
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
StringBuilder builder = new StringBuilder(); // used to store string and append data further if you want
while (rs.next()) {
builder.append(rs.getString("ItemName").append(","); // adding data/Item name to builder and appending comma after adding item name
}
if(builder.length() > 0){ // if there's some data inside builder
builder.setLength(builder.length() - 1); // remove last appended comma from builder
}
System.out.println("Command Separated Data" + builder.toString()); // final data of item name
}
Other way is to concate result from SQL itself.(here's a MySQL compatible code)
String sql = "SELECT group_concat(`ItemName`) as items FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
String data = "";
while (rs.next()) {
data = rs.getString("items")
}
System.out.println("Command Separated Data" + data);
}
I have a JDBC program that takes records from a MySQL database and prints out the results. The user can select which results they want from the database by selecting different checkboxes to only display certain results.
Here is the method which gets the records and prints them out:
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
result += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
result += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
result += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
result += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
result += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
result += zip + " ";
}
// print the results
}
System.out.println(result);
results.setText(result);
stmt.close();
}
Currently, if I were to select say the first three checkboxes, I would get the output:
1 Smith, Tim 12 Elm St 2 Jones, Tom 435 Oak Dr 3 Avery, Bill 623 Ash Ave 4 Kerr, Debra 1573 Yew Crt
However, the output I am after is:
1, Smith, Tim, 12 Elm St
2, Jones, Tom, 435 Oak Dr
3, Avery, Bill, 623 Ash Ave
4, Kerr, Debra, 1573 Yew Crt
Is there any way I can add a new line after each record in the database, as well as maybe the commas in between items in each record? I am new to JDBC and MySQL connectivity, so any help or tips is appreciated.
You can print every single result just before the end of while loop, then it'll print every record in new line.
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
String singleResult = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
singleResult += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
singleResult += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
singleResult += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
singleResult += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
singleResult += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
singleResult += zip + " ";
}
System.out.println(singleResult);
result +=singleResult;
}
//System.out.println(result);
results.setText(result);
stmt.close();
}
Or you can append line separator, just before closing while loop
System.out.println(singleResult);
result +=singleResult;
result +="\n";
First, I would use a StringJoiner to gather the elements. Then, I would eliminate the many local temporary variables. Finally, I would use println in the loop and another StringJoiner for the final result. Like,
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
StringJoiner result = new StringJoiner(System.lineSeparator());
while (rs.next()) {
StringJoiner lineJoiner = new StringJoiner(", ");
if (cb1.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
lineJoiner.add(rs.getString("name"));
}
if (cb3.isSelected()) {
lineJoiner.add(rs.getString("address"));
}
if (cb4.isSelected()) {
lineJoiner.add(rs.getString("city"));
}
if (cb5.isSelected()) {
lineJoiner.add(rs.getString("state"));
}
if (cb6.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("zip")));
}
System.out.println(lineJoiner);
result.add(lineJoiner.toString());
}
results.setText(result.toString());
stmt.close();
}
You could also do the same thing with Collection(s) like,
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
List<String> msg = new ArrayList<>();
while (rs.next()) {
List<String> al = new ArrayList<>();
if (cb1.isSelected()) {
al.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
al.add(rs.getString("name"));
}
if (cb3.isSelected()) {
al.add(rs.getString("address"));
}
if (cb4.isSelected()) {
al.add(rs.getString("city"));
}
if (cb5.isSelected()) {
al.add(rs.getString("state"));
}
if (cb6.isSelected()) {
al.add(String.valueOf(rs.getInt("zip")));
}
String line = al.stream().collect(Collectors.joining(", "));
System.out.println(line);
msg.add(line);
}
results.setText(msg.stream().collect(Collectors.joining(System.lineSeparator())));
stmt.close();
Prefer whichever you find most readable.
So I am creating an online bank transfer section where the user can transfer money between their account. I have a drop down box where it will show the amount of accounts the user has. I am not sure if I am doing this correctly. Here is my code so far:
transfer-page.jsp
<form name="transfer" action="TransferServlet" method="post">
<%
String email = (String) session.getAttribute("email");
String getAccountType = UserProfileService.getAccountTypeByEmail(email);
int count = UserProfileService.getAmountOfAccounts(email);
%>
From Account: <select name="AccountType">
<%
for(int i = 0; i < count; i++)
{
%>
<option> <%=getAccountType %>
<%
}
%>
</option>
</select>
</form>
Database Class:
public static String getAccountTypeByEmail(String email)
{
// AccountType accountType = new AccountType();
String getAccountType = "";
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT * FROM accountType WHERE email=?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
ResultSet rs = stmt.executeQuery(query);
rs.next();
getAccountType = rs.getString("accountType");
// accountType.setAccountType(getAccountType);
} catch (Exception e)
{
System.out.println(e);
}
// return accountType;
return getAccountType;
}
public static int getAmountOfAccounts(String email)
{
int count = 0;
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT count(*) FROM accountType WHERE email=?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
String account = rs.getString("accountType");
count++;
}
} catch (Exception e)
{
System.out.println(e);
}
return count;
}
I do not know under what circumstances you will appear in the drop-down box shows the amount of the account. An account binding more than one bank card?
String getAccountType = UserProfileService.getAccountTypeByEmail(email); your method getAccountTypeByEmail(String email) return only one result,why you loop show it.
I'm working on shifts manager program which calculates monthly salary and etc.
the program based on SQLite database which keeps getting updated by the user input.
my question is , how can i use the SQLite function in java to retrieve information, lets say monthly salary in one command (i know i can use " select sum(tips) between date1 and date2",but how can i get the function result inside a variable?)
so far i've created a function which gets two dates and retrieves all the shifts salary between these dates and summarise them with ResultSet.
here's my code:
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select tips from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum += rs.getInt("tips");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}
I edited your code.
Note that in case you select the sum of the tips, the column name changes. You also get only one row with one column as your result, so you should not need the while loop anymore.
The sum of the tips is now saved in the variable sum
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select sum(tips) from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum = rs.getInt("sum(tips)");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}