There was an error parsing the query - c#

I am writing a program in C# using Visual Studio 2010 and gets an error when retrieving data from a .sdf file.
private void BasicSearch_button_Click(object sender, EventArgs e)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source=" + Path.Combine(Application.StartupPath, "FRAT_DB.sdf") + ";Password=P#ssw0rd;Persist Security Info=False;Max Database Size=256");
string query = #"SELECT Person.PersonID, Person.Name, PhotoTags.PhotoID, Photo.Path, Photo.Location, Person.Age, Person.P_Group, Person.Email, Photo.Date "+
"FROM Person INNER JOIN PhotoTags ON Person.PersonID = PhotoTags.PersonID INNER JOIN "+
"PhotoON PhotoTags.PhotoID = Photo.PhotoID "+"WHERE (Person.Name LIKE '%%')";
if (txtName1.Text.Trim().ToString() == "" || txtName2.Text.Trim().ToString() == "")
{ MessageBox.Show("Enter Both, Name1 and Name2"); return; }
else if (radioButtonAND.Checked)
{
query = #"select pt.PhotoID,Photo.Path,photo.Location, Photo.Date from Person p inner join PhotoTags pt on p.PersonID=pt.PersonID inner join Photo on pt.photoID=photo.photoID where Name like '%" + txtName1.Text + "%' and pt.Photoid in (select pt.PhotoID from Person p inner join PhotoTags pt on p.PersonID=pt.PersonID where Name like '%" + txtName2.Text + "%')";
}
else
{
query = #"SELECT DISTINCT Person.PersonID, Person.Name, PhotoTags.PhotoID, Photo.Path, Photo.Location, Person.Age, Photo.Date
FROM Person INNER JOIN PhotoTags ON Person.PersonID = PhotoTags.PersonID INNER JOIN
PhotoON PhotoTags.PhotoID = Photo.PhotoID
WHERE (Person.Name LIKE '%%')";
query += " AND (Person.Name like '%" + txtName1.Text + "%' OR Person.Name like '%" + txtName2.Text + "%')";
}
if (cn.State == ConnectionState.Closed) cn.Open();
SqlCeCommand cm_Search = new SqlCeCommand(query, cn);
try
{
SqlCeDataReader rdr = cm_Search.ExecuteReader();
List<PersonPhoto> personPhoto = new List<PersonPhoto>();
List<PersonPhotoWithoutName> personPhotoWithoutName = new List<PersonPhotoWithoutName>();
bool HasRows = rdr.Read();
if (HasRows)
{
while (rdr.Read())
{
if (radioButtonAND.Checked)
{
personPhotoWithoutName.Add(new PersonPhotoWithoutName
{
PhotoID = Convert.ToInt32(rdr["PhotoID"].ToString()),
Location = rdr["location"].ToString(),
Date = rdr["Date"] != null ? Convert.ToDateTime(rdr["Date"]) : DateTime.Now,
path = rdr["path"].ToString(),
});
}
else
{
personPhoto.Add(new PersonPhoto
{
Name = rdr["Name"].ToString(),
Location = rdr["location"].ToString(),
Date = rdr["Date"] != null ? Convert.ToDateTime(rdr["Date"]) : DateTime.Now,
path = rdr["path"].ToString()
});
}
}
rdr.Close();
}
else
{ MessageBox.Show("No Records Found"); selectedPictureBox.Image = null; rdr.Close(); }
if (personPhoto.Count > personPhotoWithoutName.Count)
{
DataGridPersons.DataSource = personPhoto;
DataGridPersons.Refresh();
}
else
{
DataGridPersons.DataSource = personPhotoWithoutName;
DataGridPersons.Refresh();
}
}
catch (Exception exp)
{
throw exp;
}
if (cn.State != ConnectionState.Closed) cn.Close();
}
Whenever I try to search for someone this exception error comes up:
There was an error parsing the query. [ Token line number = 3,Token
line offset = 18,Token in error = . ]
Any help?
thanks in advance!

I suspect this is the problem:
... INNER JOIN
PhotoON PhotoTags.PhotoID = Photo.PhotoID ...
I suspect you meant:
... INNER JOIN
Photo ON PhotoTags.PhotoID = Photo.PhotoID ...
Note the space between Photo and ON. I suspect you could reformat your query so this would be rather clearer, to be honest...

Related

Executing a query with no search term causes System.StackOverflow Exception in System.Runtime.Serialization.dll

I 'm dealing with a query which results in above mentioned error when called with no or limited search string.
The table is 30k records big and when the query is fired with no search string I would expect the database to return all records and have Visual Studio put them in a table (ASP.net), however, if the query is fired like above the StackOverflow error is returned :(
If I fire the query with a more specific search string the script seems to work normal and results are being returned as expected.
I have been googling and all seems to point to an infinite loop or recursion but returning records make me believe it might be another problem.
The query:
SqlConnection conn = new SqlConnection(_cstring);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
SqlDataReader dr;
if (mode == "zoek_met_zoekterm")
{
cmd.CommandText = "select W1.id, W1.soort_brief, W1.omschrijving, W1.referentie, W1.url, W1.factuur, W3.naam, W3.klantnummer, W4.omschrijving AS w4_omschr, W4.referentie AS w4_ref, substring(W1.referentie,6,2) as w1_jaar, W1.parent AS w1_parent from brief W1 left join brief W4 on W1.parent = W4.id join klant W3 on W3.klantnummer = W1.klantnummer where W1.referentie in (select referentie from brief where substring(referentie,6,2) = #jaar) and (W3.klantnummer like #zoekterm or W1.referentie like #zoekterm or W1.omschrijving like #zoekterm or W3.naam like #zoekterm or W4.omschrijving like #zoekterm) order by W1.id";
cmd.Parameters.Clear();
cmd.Parameters.Add("#zoekterm", SqlDbType.VarChar).Value = "%" + (string)parameters["zoekterm"] + "%";
string jaar = parameters["jaar"].ToString();
jaar = jaar.Substring(2, 2);
cmd.Parameters.Add("#jaar", SqlDbType.VarChar).Value = jaar;//(Int32)parameters["jaar"];
base.LogQuery(cmd);
dr = cmd.ExecuteReader();
while (dr.Read())
{
CBrief brief = new CBrief();
brief.Id = dr.GetInt32(0);
brief.SoortBrief = (Enums.SoortBrief)dr.GetInt32(1);
brief.Omschrijving = Functies.Decrypt(dr.GetString(2), EncryptData);
brief.Referentie = Functies.Decrypt(dr.GetString(3), EncryptData);
brief.Url = Functies.Decrypt(dr.GetString(4), EncryptData);
brief.Factuur = (Enums.SoortDocument)dr.GetInt32(5);
brief.Klantnummer = dr.GetInt32(7);
if (dr.GetString(2).Length == 0)
{
if (!dr.IsDBNull(9) && !dr.IsDBNull(8))
brief.Omschrijving = dr.GetString(9) + " " + dr.GetString(8);
}
ret_value.Add(brief);
}
dr.Close();
dr.Dispose();
}
And the function that calls the query:
public List<CBrief> GetBriefOverzicht(string zoekterm, int jaar)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("zoekterm", zoekterm);
parameters.Add("jaar", jaar);
if (zoekterm.Length == 0)
{
return _dal.brief_search(parameters, "geen_invoer");
}
return _dal.brief_search(parameters, "zoek_met_zoekterm");
}
And last but not least the function that builds the table to display in the web application:
protected void Bzoeken_Click(object sender, EventArgs e)
{
string zoekterm = TBzoekterm.Text;
DateTime nu = DateTime.Now;
int jaar = nu.Year;
List<CBrief> brieven = br_rbs.GetBriefOverzichtWijzigen(zoekterm);
StringBuilder overzicht = new StringBuilder("<table class=\"tabel-beheer-1\">");
foreach (CBrief b in brieven)
{
List<CBijlage> bijlagen = new List<CBijlage>();
CKlant k = sec.GetKlant(b.Klantnummer);
string klantnaam = k.Naam;
string richting = "";
if (b.OmschrijvingAanwezig == true)
{
bijlagen = br_rbs.GetBijlagenBrieven(b.Id);
}
if (b.SoortBrief == Enums.SoortBrief.Inkomend) richting = "van: "; else richting = "naar: ";
// MG10082017 Ik heb hier twee icoontjes in elkaar geflanst om te testen. Deze moeten nog aangepast worden zodat ze in het geheeel passen.
overzicht.AppendLine("<tr><td><img src=\"/images/bg/document.jpg\" alt=\"open document\"></td><td><img src=\"/images/bg/detail.jpg\" alt=\"details\"></td><td><b>" + b.Referentie + "</b></td><td><i>" + b.SoortBrief.ToString() + " " + richting + "</i> " + klantnaam + "</td><td><b> " + b.Factuur.ToString() + ":</b> " + b.Omschrijving /*+"</td><td>"*/);
if (bijlagen.Count > 0)
{
foreach (CBijlage bijl in bijlagen)
{
overzicht.AppendLine("</br> " + bijl.Naam + "");
}
}
}
overzicht.AppendLine("</td></tr></table>");
Loverzicht.Text = overzicht.ToString();
}
The error usually points to: System.Web.dll or w3wp.exe (when not ran in debug mode). If my assumption is wrong and it seems to be an infinite loop or recursion, how am I going to find this?
The query works flawless in MS-SQL management console.
The Problem is not an infinite loop!
The Problem lies in the UI.
You can't display 30k units at once without a StackOverflow-Exception.
You should call pages of maybe 20 or 30 units at once with an pageIndex.
This way, your application will perform better and avoid such errors.

Continuation about Getting date between two dates

My datagridview displays date with the year 2015, even if I set my two datetimepickers from two different dates but with the same year (2016).
Heres my code..
public static List<Retailer> GetDataAllRetailer(DateTime past, DateTime present)
{
List<Retailer> data = new List<Retailer>();
MySqlConnection con = DBConnection.ConnectDatabase();
try
{ // AND
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tablename + " WHERE (date BETWEEN '" + past.ToString("MM-dd-yyyy") + "' AND '" + present.ToString("MM-dd-yyyy") + "') ", con);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Retailer rawData = new Retailer();
rawData.Date = reader.GetString(1);
rawData.Walletid = reader.GetString(0);
rawData.Fname = reader.GetString(2);
rawData.Lname = reader.GetString(3);
rawData.Birthdate = reader.GetString(4);
rawData.Address = reader.GetString(5);
rawData.Province = reader.GetString(6);
rawData.City = reader.GetString(7);
rawData.Balance = reader.GetDouble(8);
rawData.Frozen = reader.GetDouble(9);
rawData.Sponsor_id = reader.GetString(10);
rawData.Share = reader.GetDecimal(11);
rawData.Email = reader.GetString(12);
rawData.Password = reader.GetString(13);
rawData.Type = reader.GetInt32(14);
data.Add(rawData);
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
return data;
}
}
If the table column is varchar, then I suggest you to convert it to date to do the search appropriately as follows:
SELECT * FROM Table WHERE
CONVERT(DATE, FromDate) >= CONVERT(DATE, '2016-09-03')
AND CONVERT(DATE, ToDate) <= CONVERT(DATE, '2016-09-13')

SELECT COUNT query not producing the result I'm expecting

I have a SELECT COUNT query that is used to determine whether the user has already been given a grade or not and if that particular user has a grade already the button to submit a grade will become invisible. However, the button still appears even though I've given that student a grade. When I launch in debugging mode the value of the query is null. Below is the code in the method:
String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
String modOnpwayModID = "SELECT id FROM module_on_pathway WHERE module_id = '" + modDropDown.SelectedValue + "'";
SqlCommand modOnpwayModIDQuerycmd = new SqlCommand(modOnpwayModID, myConnection);
Int32 modOnpwayModIDResult = Convert.ToInt32(modOnpwayModIDQuerycmd.ExecuteScalar().ToString());
Label lb = (Label)e.Item.FindControl("user_idLabel");
String userIDLabel = lb.Text.ToString();
Int32 usrIDVal = Convert.ToInt32(userIDLabel);
String gradeSelectionQuery = "SELECT COUNT(student_module_grade.grade) FROM student_module_grade INNER JOIN classlist ON student_module_grade.classlist_id = classlist.classlist_id INNER JOIN student_assignment_grade ON student_module_grade.classlist_id = student_assignment_grade.classlist_id INNER JOIN assignments ON student_assignment_grade.assignment_id = assignments.assignment_id WHERE student_module_grade.module_on_pathway_id ='" + modOnpwayModIDResult + "'AND classlist.user_id = '" + userIDLabel + "'";
SqlCommand gradeSelectionQuerycmd = new SqlCommand(gradeSelectionQuery, myConnection);
Int32 gradeCount = Convert.ToInt32(gradeSelectionQuerycmd.ExecuteScalar().ToString());
//See if a final score has been given already- can then be changed by the admin if it needs to be changed
if (gradeCount == 0)
{
submitmodMark1st.Visible = true;
//All elements for grade submission made invisible- admin will be unable to change the grade
//TB.Visible = false;
//changedFlagVal.Text = "The grade for this module has already been changed for the selected student";
//changedFlagVal.Visible = true;
//changedFlagVal.ForeColor = System.Drawing.Color.Red;
}
else
{
submitmodMark1st.Visible = false;
}
String repeatGradeSelectionQuery = "SELECT COUNT(student_module_repeat_grades.grade) FROM student_module_repeat_grades INNER JOIN classlist ON student_module_repeat_grades.classlist_id = classlist.classlist_id INNER JOIN student_assignment_grade ON student_module_repeat_grades.classlist_id = student_assignment_grade.classlist_id INNER JOIN assignments ON student_assignment_grade.assignment_id = assignments.assignment_id WHERE student_module_repeat_grades.module_on_pathway_id ='" + modOnpwayModIDResult + "'AND classlist.user_id = '" + userIDLabel + "'";
SqlCommand repeatGradeSelectionQuerycmd = new SqlCommand(repeatGradeSelectionQuery, myConnection);
Int32 repeatGradeCount = Convert.ToInt32(repeatGradeSelectionQuerycmd.ExecuteScalar().ToString());
if (repeatGradeCount == 0)
{
submitmodMark1st.Visible = true;
}
else
{
//All elements for grade submission made invisible- admin will be unable to change the grade
//TB.Visible = false;
changedFlagVal.Text = "The grade for this module has already been changed for the selected student";
changedFlagVal.Visible = true;
changedFlagVal.ForeColor = System.Drawing.Color.Red;
submitmodMark1st.Visible = false;
}
You could convert that into a stored procedure like this in your SQL-
CREATE PROC getCountStudentModule #pathwayId int, #userID int
AS
BEGIN
SELECT COUNT(student_module_repeat_grades.grade) AS CntRepeatGrades
FROM student_module_repeat_grades
INNER JOIN classlist
ON student_module_repeat_grades.classlist_id = classlist.classlist_id
INNER JOIN student_assignment_grade
ON student_module_repeat_grades.classlist_id = student_assignment_grade.classlist_id
INNER JOIN assignments
ON student_assignment_grade.assignment_id = assignments.assignment_id
WHERE student_module_repeat_grades.module_on_pathway_id = #pathwayId
AND classlist.user_id = #userID
END
GO
And then do something like this-
public bool CheckStatus()
{
bool status = false;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("getCountStudentModule", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pathwayid", modOnpwayModIDResult);
cmd.Parameters.AddWithValue("#userID", userIDLabel);
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
string active = rdr["CntRepeatGrades"].ToString();
if (active == "0")
{
status = true;
}
else
{
status = false;
}
}
}
return status;
}
}
And then you can do a check like this for your button-
bool status = CheckStatus();
if (status)
{
submitmodMark1st.Visible = true;
}
else
{
//All elements for grade submission made invisible- admin will be unable to change the grade
//TB.Visible = false;
changedFlagVal.Text = "The grade for this module has already been changed for the selected student";
changedFlagVal.Visible = true;
changedFlagVal.ForeColor = System.Drawing.Color.Red;
submitmodMark1st.Visible = false;
}

Timeout connection error while executing this piece of code in ASP.NET 2.0 and C#

I am using the below code to grab the page tiles, meta description from database created in SQL Server 2005. My site is built with ASP.NET 2.0 and C#.
On page_load I am executing this code:
string query = "select MetaDescription, MetaKeywords, H1Text, Ptitle, H2Text FROM SeoText Where CatalogItemId ='" + this.CurrentEnsemble.ItemId + "'";
SqlConnection myconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBconnection"].ConnectionString);
SqlCommand SqlCmd = null;
SqlCmd = new SqlCommand(query, myconnection);
SqlDataAdapter ad = new SqlDataAdapter(SqlCmd);
DataTable dt = new DataTable();
ad.Fill(dt);
if (dt.Rows[0]["Ptitle"].ToString() == "")
{
this.Page.Title = this.CurrentEnsemble.Title;
}
else
{
this.Page.Title = this.CurrentEnsemble.Title + " " + dt.Rows[0]["Ptitle"].ToString();
}
HtmlMeta metaDesc = (HtmlMeta)Page.Header.FindControl("metaDesc");
if (dt.Rows[0]["MetaDescription"].ToString() == "")
{
metaDesc.Attributes.Add("Content", this.CurrentEnsemble.Title );
}
else
{
metaDesc.Attributes.Add("Content", dt.Rows[0]["MetaDescription"].ToString());
}
HtmlMeta metaKey = (HtmlMeta)Page.Header.FindControl("metaKey");
if (dt.Rows[0]["MetaKeywords"].ToString() == "")
{
metaKey.Attributes.Add("Content", "site general text");
}
else
{
metaKey.Attributes.Add("Content", dt.Rows[0]["MetaKeywords"].ToString());
}
HtmlGenericControl h1 = (HtmlGenericControl)Master.Master.Master.FindControl("h1top");
if (dt.Rows[0]["H1Text"].ToString() == "")
{
h1.InnerText = "site general text";
}
else
{
h1.InnerText = this.CurrentEnsemble.Title + " " + dt.Rows[0]["H1Text"].ToString();
}
HtmlGenericControl h2 = (HtmlGenericControl)Master.Master.Master.FindControl("h2bottom");
if (dt.Rows[0]["H2Text"].ToString() == "")
{
h2.InnerText = "site general text";
}
else
{
h2.InnerText = this.CurrentEnsemble.Title + " " + dt.Rows[0]["H2Text"].ToString();
}
The error is thrown at
ad.Fill(dt)
I am not sure where I am making the mistake.
Thanks and appreciate it
Try adding with (nolock) statements to your statment. Similar problem here: SqlDataAdapter.Fill() Timeout - Underlying Sproc Returns Quickly

error: sql command not properly ended

I have to search the employee details, which is contained within 3 tables. I have used joins in the query query, but it shows error when I press the search button:
sql command not properly ended
c# coding:
try {
//Search Employee Details
Oracle.DataAccess.Client.OracleConnection cn = new Oracle.DataAccess.Client.OracleConnection();
cn.ConnectionString = "user id=system; password=system;";
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.Connection = cn;
//cn = new Oracle.DataAccess.Client.OracleConnection();
cmd.CommandText = " select deposit.loanid,
form1.empedoj,
form1.empshare,
sharecapital.shareint,
sharecapital.loandt,
sharecapital.loandeduc,
sharecapital.dividend,
sharecapital.sharetot
from form1,
deposit,
sharecapital
where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "'"; // shows sql command not properly ended
Oracle.DataAccess.Client.OracleDataAdapter ada = new Oracle.DataAccess.Client.OracleDataAdapter(cmd);
System.Data.DataTable dt = new DataTable();
dt.Clear();
ada.Fill(dt);
//Display in Textbox
if (dt.Rows.Count > 0) {
txtlnid.Text = dt.Rows[0].ItemArray[0].ToString();
admdate.Text = dt.Rows[0].ItemArray[1].ToString();
txtadmamt.Text = dt.Rows[0].ItemArray[2].ToString();
txtadmint.Text = dt.Rows[0].ItemArray[3].ToString();
loandt.Text = dt.Rows[0].ItemArray[4].ToString();
txtlnamt.Text = dt.Rows[0].ItemArray[5].ToString();
txtlnint.Text = dt.Rows[0].ItemArray[6].ToString();
txtsctot.Text = dt.Rows[0].ItemArray[7].ToString();
}
if (cn.State == ConnectionState.Closed) {
cn.Open();
}
string str;
str = cmd.ExecuteScalar().ToString();
if (str != null) {
MessageBox.Show("Record Found");
} else {
MessageBox.Show("ID not Match");
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Your SQL statement becomes
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
I suspect it should be:
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID
AND SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
Also, you have a 3-table join without the correct join conditions, the query is highly likely to return a Cartesian product.
Have you tried putting a semicolon at the end of your query string?
cmd.CommandText = " select deposit.loanid, form1.empedoj, form1.empshare,
sharecapital.shareint, sharecapital.loandt, sharecapital.loandeduc,
sharecapital.dividend, sharecapital.sharetot from form1, deposit ,
sharecapital where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "';";

Categories

Resources