How to check if the ResultSet is empty? - resultset

<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.sql.*"%><%#page import = "java.sql.ResultSet" %>
<%#page import = "java.sql.Connection" %>
<!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>Getting Database Connection</title>
</head>
<body>
<%
ResultSet result = null ;
Connection connection1 = null;
try
{
String driverName1 = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName1);
String serverName = "localhost";
String portNumber = "1521";
String sid = "XE";
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + sid;
String username = "SYSTEM";
String password = "password";
connection1 = DriverManager.getConnection(url, username, password);
out.println(connection1.isClosed());
String Name = request.getParameter("name");
String Age = request.getParameter("age");
int AgeConvert = Integer.parseInt(Age);
String ADR = request.getParameter("address");
String sqlInsert = " INSERT INTO ADDRESS (NAME,AGE,ADR) VALUES ('" + Name + "' , " + AgeConvert + ", '" + ADR +"')";
Statement stm = connection1.createStatement();
stm.execute(sqlInsert);
out.println(" User Created");
}
catch(Exception e )
{
out.println("User not created");
e.printStackTrace();
}
%>
<table>
<tr>
<td> <b>To search the User Please enter the name in the below box </b> </td>
</tr>
<tr>
<td> Name </td>
<td> <input type = "text" name ="userName" /> </td>
</tr>
<tr>
<td> <input type ="submit" value = "Search" /></td>
</tr>
</table>
<% ResultSet results = null ;
String userNameToBeSearched = request.getParameter("userName");
String sqlselect = " SELECT * FROM ADDRESS WHERE NAME ='"+userNameToBeSearched+"'";
Statement stm2 = connection1.createStatement();
results = stm2.execute(sqlselect);
**// getting error in this loop it says can convert boolean to ResultSet please help me**
if (results.next()) {
do {
%>
<TABLE BORDER="1">
<TR>
<TH>Name</TH>
<TH>Age</TH>
<TH>Address</TH>
</TR>
<TR>
<TD> <%= results.getString(1) %> </TD>
<TD> <%= results.getInt(2) %> </TD>
<TD> <%= results.getString(3) %> </TD>
</TR>
</TABLE>
<%
} while (results.next());
} else
{
out.println("User not found");
}
%>
</body>
</html>

if(!resultSet.isBeforeFirst()){
System.out.println("resultset contin no rows");
}
isBeforeFirst() returns true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows

try stm2.exexuteQuery()
This will grab the result set

ResultSet.next() returns false if no more rows are found, otherwise true.

Would it not work doing:
if(!resultSet.next()){
System.out.println("Rows not found");
}
.next() will go through the rows and validate if there is any row.

Related

Posting to Servlet From Two Forms Within HTML Page

Solution: Just added null default values to the HTML parameters. Seems to have solved it!
So I have an admin page (HTML) with two forms. First form is to add to an SQL database and has 4 input boxes, second form deletes from a SQL database and has 1 input box. If I use the first form, everything is OK. But if I leave the first form empty and just put a value for the 2nd form, I get an NumberFormatException for String = "" I can only assume because the first form is empty. I'm trying to have the user either fill the first form and leave the 2nd empty, or vice versa. Any advice on how to better approach this would be great.
This is my HTML page
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Admin</title>
<link rel="stylesheet" href="myStyle.css">
</head>
<body>
<h1>Welcome to the admin page.</h1>
<h2>Please enter the new product to be added:</h2>
<form action="eShop" method="Post">
<table class="tableBox">
<tr>
<td align="left"><b>Item Code:</b></td>
<td align="left"><input type="number" name="code"></td>
</tr>
<tr>
<td align="left"><b>Item Name:</b></td>
<td align="left"><input type="text" name="name"></td>
</tr>
<tr>
<td align="left"><b>Item Price:</b></td>
<td align="left"><input type="number" name="price"></td>
</tr>
<tr>
<td align="left"><b>Is Taxable:</b></td>
<td align="left"><input type="text" name="taxable"></td>
<tr>
<td align="center" colspan="2"><input type="submit" name="action" value="Update!"></td>
</tr>
</table>
</form>
<h2>Enter the code of the product you want to delete:</h2>
<form action="eShop" method="Post">
<table class="tableBox">
<tr>
<td align="left"><b>Item Code:</b></td>
<td align="left"><input type="number" name="code"></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" name="action" value="Delete!"></td>
</tr>
</table>
</form>
</body>
</html>
This is the section in my servlet that gets the parameters
else if(request.getParameter("action").equals("Delete!")) {
DataAccessImpl temp = new DataAccessImpl();
int code = Integer.parseInt(request.getParameter("code"));
temp.deleteItem(code);
}
This is the DataAccessImpl class used in the servlet, particularly the method that will delete the row.
public void deleteItem(int code) {
connect();
String deleteStm = ("DELETE FROM ProductCatalogue WHERE code = " + code);
PreparedStatement pstm = null;
System.out.println("Beginning to delete product from database...");
try {
pstm = conn.prepareStatement(deleteStm);
System.out.println("Delete complete!");
}
catch(SQLException e) {
e.printStackTrace();
}
}
in first form name your submit button like this:
<input type="submit" name="updateAction" value="Update!">
in second form name your submit button like this:
<input type="submit" name="deleteAction" value="Delete!">
Servlet Code should be like this:
else if(request.getParameter("deleteAction").equals("Delete!")) {
DataAccessImpl temp = new DataAccessImpl();
int code = Integer.parseInt(request.getParameter("code"));
temp.deleteItem(code);
}

How to set header value in kendo grid row template

I am using jquery kendo grid in my project where i used row template to show three column in one row. Below is the code:
<table id="grid" style="width:100%">
<thead style="display:none">
<tr>
<th>
Details
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3"></td>
</tr>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<script id="rowTemplate" type="text/x-kendo-tmpl">
<div>
<span class="name" style="font-size:medium">#: FirstValue #</span>
<span class="name" style="font-size:medium">#: SecondValue #</span>
</div>
<tr>
<td style="width:30%">
#: GetName #
<span class="name" style="font-size:14px; color:green">#: Designation #</span>
<span class="name" style="font-family:Arial; font-size:small">#: Company #</span>
</td>
</tr>
</script>
in the above code i am just passing my model data it's working fine but when i added one div which have value firstName and LastName so it is also repeating with this data but i want to to show separately.How do i show it separately so that it should not repeat with grid.
there is one problem in your html template.
Please replace '#' with 'Javascript:void(0)'.
Error:- #: GetName #
Fix:- #: GetName #
Hope that's work for you.
http://jsfiddle.net/parthiv89/t0w3ht6m/1/
if you like then don't forget to like.
I got solution by own, Firstly i changed code in my schema like this:
schema: {
parse: function (data) {
var items = [];
for (var i = 0; i < data.data.length; i++) {
if (data.data[i].CorrectValue != null && data.data[i].SearchValue != null) {
$("#spnSR")[i].innerHTML = "<b>"+"Get results for this text: "+"</b>"+data.data[i].CorrectValue;
$("#spnSV")[i].innerHTML = "<b>" + "Searched for this text: " +"</b>" + data.data[i].SearchValue;
}
}
var product = {
data: data.data,
total: data.total
};
items.push(product);
return (items[0].data);
},
}
Then in html i used two span to show this value which is there in for loop.
and it's working fine for me.
Thanks everyone.

Error with Dreamweaver User Authentication when using levels

I am using Dreamweavers User Authentication, and since I have introduced the use of 'levels' it just keeps erroring
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Sybase][ODBC Driver][Adaptive Server Anywhere]Syntax error near 'group' on line 1
/coding/login.asp, line 29
My code is as follows
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!--#include file="Connections/Conn_PSCRM_Demo.asp" -->
<%
' *** Validate request to log in to this site.
MM_LoginAction = Request.ServerVariables("URL")
If Request.QueryString <> "" Then MM_LoginAction = MM_LoginAction + "?" + Server.HTMLEncode(Request.QueryString)
MM_valUsername = CStr(Request.Form("usercode"))
If MM_valUsername <> "" Then
Dim MM_fldUserAuthorization
Dim MM_redirectLoginSuccess
Dim MM_redirectLoginFailed
Dim MM_loginSQL
Dim MM_rsUser
Dim MM_rsUser_cmd
MM_fldUserAuthorization = "group"
MM_redirectLoginSuccess = "quote-search.asp"
MM_redirectLoginFailed = "no_access.asp"
MM_loginSQL = "SELECT usercode, epros_password"
If MM_fldUserAuthorization <> "" Then MM_loginSQL = MM_loginSQL & "," & MM_fldUserAuthorization
MM_loginSQL = MM_loginSQL & " FROM DBA.[user] WHERE usercode = ? AND epros_password = ?"
Set MM_rsUser_cmd = Server.CreateObject ("ADODB.Command")
MM_rsUser_cmd.ActiveConnection = MM_Conn_PSCRM_Demo_STRING
MM_rsUser_cmd.CommandText = MM_loginSQL
MM_rsUser_cmd.Parameters.Append MM_rsUser_cmd.CreateParameter("param1", 200, 1, 255, MM_valUsername) ' adVarChar
MM_rsUser_cmd.Parameters.Append MM_rsUser_cmd.CreateParameter("param2", 200, 1, 255, Request.Form("password")) ' adVarChar
MM_rsUser_cmd.Prepared = true
Set MM_rsUser = MM_rsUser_cmd.Execute
If Not MM_rsUser.EOF Or Not MM_rsUser.BOF Then
' username and password match - this is a valid user
Session("MM_Username") = MM_valUsername
If (MM_fldUserAuthorization <> "") Then
Session("MM_UserAuthorization") = CStr(MM_rsUser.Fields.Item(MM_fldUserAuthorization).Value)
Else
Session("MM_UserAuthorization") = ""
End If
if CStr(Request.QueryString("accessdenied")) <> "" And true Then
MM_redirectLoginSuccess = Request.QueryString("accessdenied")
End If
MM_rsUser.Close
Response.Redirect(MM_redirectLoginSuccess)
End If
MM_rsUser.Close
Response.Redirect(MM_redirectLoginFailed)
End If
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div>
<h1>Coding</h1>
<p>Enter your username and password below to login</p>
<form ACTION="<%=MM_LoginAction%>" METHOD="POST" id="coding_login" name="coding-login">
<table width="50%" border="0" cellspacing="2" cellpadding="2">
<tr>
<th scope="row">Username:</th>
<td><label for="usercode"></label>
<input name="usercode" type="text" required id="usercode" size="5" maxlength="3"></td>
</tr>
<tr>
<th scope="row">Password:</th>
<td><label for="password"></label>
<input name="password" type="password" id="password" size="10" maxlength="25" required></td>
</tr>
<tr>
<th scope="row"> </th>
<td><input type="submit" name="Login" id="Login" value="Login"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Any help would be greatly accepted.
"group" is a reserved word in sybase (and I imagine many other database systems)
on line 16 try
MM_fldUserAuthorization = """group"""

ASP connecting to SQL Server database

<%
'declare the variables
Dim Recordset
Dim sql
dim Conn
Dim name1,email1,phone1,company1,title1
name1 = request.form("TxtName")
email1 = request.form("TxtEmail")
phone1 = request.form("TxtPhone")
company1 = request.form("TxtCompany")
title1 = request.form("TxtJob")
'create an instance of the ADO connection and recordset objects
Set Conn= Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")
'open the connection to the database
Conn.ConnectionString = "DSN=blah;User Id=...;Password=...;Database=...."
'Open the recordset object executing the SQL statement and return records
Recordset.Open
Conn.open
sql="INSERT INTO register (Name, email, phonenumber, company, title)"
sql=sql & "values ('"& name1 &"','"& email1 &"','"& phone1 &"','"& company1 &"','"& title1 &"')"
Conn.Execute(sql)
Conn.Close()
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample Registration Page</title>
</head>
<body>
<form name"form" action="">
<table>
<tr>
<td>Full Name:</td>
<td>
<input name="TxtName" id="TxtName" type="text" />
</td>
</tr>
<tr>
<td>Email:</td>
<td>
<input name="TxtEmail" id="TxtEmail" type="text" />
</td>
</tr>
<tr>
<td>Phone:</td>
<td>
<input name="TxtPhone" id="TxTPhone" type="text" />
</td>
</tr>
<tr>
<td>Company:</td>
<td>
<input name="TxtCompany" id="TxtCompany" type="text" />
</td>
</tr>
<tr>
<td>Job Title:</td>
<td>
<input name="TxtJob" id="TxtJob" type="text" />
</td>
</table>
<input name="button" ID="Button1" value="submit" type="Submit" />
</form>
</body>
</html>
I get an error 500 message when I run this page, I have no idea where my mistake is.
I also did make the DSN connection with name called blah to my SQL Server.
I ran the ASP part alone and it works, however the database section is where my problem lies. I really appreciate any help since I'm relatively new to this.
First, you should activate the friendly display of errors on your web server in order to know exactly what and where the error is instead of the generic, say nothing Error 500 that you are getting at this moment.
Second, in the meantime, add a couple of Response.write followed by Response.Flush to see what's going and where; for example to display the result of the building of the sql string:
sql = ...
response.write sql & "<br>"
response.flush
Second, you try to open a Recordset with no associated Command object or sql query string; you cannot do that and in fact, you don't need any Recordset here because your have an Insert query, not a Select query.
Finally, using a DSN with ADODB is a bad idea. DSN are for ODBC and by using ODBC under ADODB, you are adding an old, useless layer to your data connection. You should instead use the latest native OLEDB provider for your SQL-Server. Search the web for Connection String and you will get a few web sites with full details on the available providers along with their connection strings.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample Registration Page</title>
</head>
<body>
<form action="registration.asp" method="POST" name="form1">
<table>
<tr>
<td>Full Name:</td>
<td><input name="TxtName" id="TxtName" type="text" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="TxtEmail" id="TxtEmail" type="text" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input name="TxtPhone" id="TxTPhone" type="text" /></td>
</tr>
<tr>
<td>Company:</td>
<td><input name="TxtCompany" id="TxtCompany" type="text" /></td>
</tr>
<tr><td>Job Title:</td>
<td><input name="TxtJob" id="TxtJob" type="text" /></td>
</table>
<input name="button" ID="Button1" value="submit" type="Submit" />
</form>
</body>
</html>
<%
If Request.ServerVariables("REQUEST_METHOD") = "POST" then
Dim Conn, Rs, ConnString, SQL_Insert
Dim name1,email1,phone1,company1,title1
name1 = request.form("TxtName")
email1 = request.form("TxtEmail")
phone1 = request.form("TxtPhone")
company1 = request.form("TxtCompany")
title1 = request.form("TxtJob")
Set Conn= Server.CreateObject("ADODB.Connection")
ConnString = "DSN=blah;User Id=...;Password=...;Database=...."
Conn.Open ConnString
SQL_Insert="INSERT INTO register (Name, email, phonenumber, company, title)" & _
"values ('"& name1 &"','"& email1 &"','"& phone1 &"','"& company1 &"','"& title1 &"');"
Conn.Execute SQL_Insert
Conn.Close
Set Conn = Nothing
Set SQL_Insert = Nothing
End If
%>
As you are not retrieving any data from database there is no need of RecordSet.
copy and paste this code in a file & name it "registration.asp"
Don't forget to replace the connection string with the actual one
for tutotrial visit www.w3schools.com
hope this is helpful
A space char seems to be missing on the SQL.
sql = "INSERT INTO register (...)SPACE-MISSING-HERE"
sql = sql & "values (...)"
Conn.Execute(sql)
Conn.Close()

MVC 4 - Return error message from Controller - Show in View

I am doing a C# project using Razor in VS2010 (MVC 4).
I need to return an error message from Controller to View and show it to the user.
What I have tried:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
ModelState.AddModelError("error", "adfdghdghgdhgdhdgda");
ViewBag.error = TempData["error"];
return RedirectToAction("Form_edit", "Form");
}
VIEW:
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary("error")
#Html.ValidationMessage("error")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Please help me to achieve this.
The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
if(ModelState.IsValid())
{
--- operations
return Redirect("OtherAction", "SomeController");
}
// here you can use a little trick
//fill the model property that holds the information for the dropdown with the data
// you haven't provided the get method but it should look something like this
model.Countries = ... some data goes here;
model.dd_value = ... some other data;
model.dd_text = ... other data;
ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
return View(model);
}
and then in the view just use :
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary(true)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
This should work okay.
If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.
other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
TempData["error"] = "someErrorMessage";
return RedirectToAction("form_Post", "Form");
}
[HttpGet]
public ActionResult form_edit()
{
do stuff here ----
ViewData["error"] = TempData["error"];
return View();
}
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
<div>#ViewData["error"]</div>
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Thanks for all the replies.
I was able to solve this by doing the following:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
return RedirectToAction("Form_edit", "Form", model);
}
public ActionResult form_edit(FormModels model, string searchString,string id)
{
string test = model.selectedvalue;
var bal = new FormModels();
bal.Countries = bal.get_contentdetails(searchString);
bal.selectedvalue = id;
bal.dd_text = "content_name";
bal.dd_value = "content_id";
test = model.error_msg;
ViewBag.head = "Heading";
if (model.error_msg != null)
{
ModelState.AddModelError("error_msg", test);
}
model.error_msg = "";
return View(bal);
}
VIEW:
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#ViewBag.error
#Html.ValidationMessage("error_msg")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
}
If you want to do a redirect, you can either:
ViewBag.Error = "error message";
or
TempData["Error"] = "error message";
You can add this to your _Layout.cshtml:
#using MyProj.ViewModels;
...
#if (TempData["UserMessage"] != null)
{
var message = (MessageViewModel)TempData["UserMessage"];
<div class="alert #message.CssClassName" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>#message.Title</strong>
#message.Message
</div>
}
Then if you want to throw an error message in your controller:
TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger alert-dismissible", Title = "Error", Message = "This is an error message" };
MessageViewModel.cs:
public class MessageViewModel
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
Note: Using Bootstrap 4 classes.