Fetching data for particular Month and year - c#

I tried Query(given below in code) But it is showing me this error
No value given for one or more required parameters.
but while debugging I am passing date as this
string monthYY = dateTimePickerMonth.Value.ToString("M-yy");
So what is the right format to check it ,how can I do it ?
Code for Query
public int GetDrID_MonthWise(string DrName,string monthYY,int refDrID)
{
int data = 0;
try
{
string sql = "Select d.DoctorID From Doctor_Master d where d.LastName + ' ' + d.FirstName = '" + DrName + "' AND Patient_registration.RegDate='" + monthYY + "' AND Patient_registration.DoctorID=" + refDrID;
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
while (rs.Read())
{
data = Convert.ToInt32(rs[0]);
}
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
return data;
}

This piece of your SQL statement informs the db engine Doctor_Master is the data source:
From Doctor_Master d
However, the WHERE clause refers to 2 fields which are not present in Doctor_Master:
Patient_registration.RegDate
Patient_registration.DoctorID
I'm unsure what you actually need. My hunch is you should INNER JOIN those tables. But I think you should design and test the query in Access, leaving c# out of the picture until after you have the Access query working as you wish.

I'm not sure exactly how you are passing your parameters but you need to specify values for all three of your parameters listed
public int GetDrID_MonthWise(string DrName,string monthYY,int refDrID)

Related

Pass data from database table to an array

i am having some trouble trying to stock one row (Id) of my table (contas) to my array (ids[ ]), according to the requisites (posicao like 'Saúde', convenio like convenio and i can't have any duplicated Id's). The variables 'e' and 'i' are merely accountants. I'm kinda new to coding so please don't judge me hard. Also it's my first post on this site + I don't know english very well.
This is my code:
// Here I select the number of Id's that are compatible with my requisites, so far so ok
cmd = new SqlCommand("select COUNT(Id) from contas where posicao like 'Saúde' and convenio like '" +convenio+"'", con);
cmd.Parameters.AddWithValue("#Id", Id);
numeroidentista = (cmd.ExecuteScalar()).ToString();
// Here I create my arrays to store the data
int[] ids = new int[Convert.ToInt32(numeroidentista)];
string[] idst = new string[Convert.ToInt32(numeroidentista)];
string[] inst = new string[Convert.ToInt32(numeroidentista)];
// And here I tryied so hard and it doesn't even matter
while (e < Convert.ToInt32(numeroidentista))
{
SqlCommand cmdao = new SqlCommand(inst[i].ToString(), con);
inst[i] = "SELECT Id FROM contas where posicao like 'Saúde' and convenio like '" + convenio + "' and Id > '" + ids[i] + "'";
SqlDataReader reader = cmdao.ExecuteReader();
if (reader.Read())
{
while (i < Convert.ToInt32(numeroidentista))
{
idst[i] = reader["Id"].ToString();
ids[i] = Convert.ToInt32(idst[i]);
i++;
}
}
e++;
reader.Close();
}
There are several problems with your code; however, the main one is, that you are using inst[i] before assigning it a value:
SqlCommand cmdao = new SqlCommand(inst[i].ToString(), con); // Using inst[i] here.
inst[i] = "SELECT Id FROM contas where posicao like 'Saúde' and convenio like '" + convenio +
"' and Id > '" + ids[i] + "'"; // But assigning it here.
Swap the lines
inst[i] = "SELECT Id FROM contas where posicao like 'Saúde' and convenio like '" + convenio +
"' and Id > '" + ids[i] + "'";
SqlCommand cmdao = new SqlCommand(inst[i].ToString(), con);
And since inst[] is a string array, no conversion to string is required:
SqlCommand cmdao = new SqlCommand(inst[i], con);
You have other superfluous conversions. You convert the COUNT(id), which is already an int to a string, just to convert it to and int again later:
//Not shown
string numeroidentista;
numeroidentista = (cmd.ExecuteScalar()).ToString();
int[] ids = new int[Convert.ToInt32(numeroidentista)];
Change it to
int numeroidentista = (int)cmd.ExecuteScalar();
int[] ids = new int[numeroidentista];
Instead of fixed size arrays I would use variable size lists (List<T>). This would make the first SELECT COUNT(Id) superfluous as well.
Another question is what type is Id in the table? You sore it in an int array, but the SQL surrounds it with apostrophes, suggesting that it has a text type. It should be and int in the table as well, in which case there should be no apostrophes in the SQL: ... and Id > " + ids[i];. You are also using ids[i] before assigning it a value.
It would be preferred to use command parameters everywhere instead of string concatenation. But since you are storing the resulting SQL, you might want to keep it this way for later reference.
Why are you using 3 different arrays. By using a class string with the 3 fields, the code would become easier. Using this class
public class ContaInfo
{
public int Id { get; set; }
public string IdString { get; set; }
public string Instruction { get; set; }
}
You could declare a list like
var contas = new List<ContaInfo>();
and then add items with
contas.Add(new ContaInfo { Id = ..., IsString = ..., Instruction = ...});
Finally, using-statements automatically close and dispose resources.
I tried to rewrite the code; however, I do not understand the logic behind all this. You are creating an array of a fixed size, but then you have 2 nested loops, potentially creating more entries than the size of the arrays.
1- You have several potential issues in your code. When you are doing the conversions, you are trusting the type in the string be convertable to your desired type for example int. Examples are Convert.ToInt32(numeroidentista) , Convert.ToInt32(idst[i]) , the recommended way is to do these using TryParse, for example :
if(!Int32.TryParse(numeroidentista, out int numeroidentistaInt))
{
Console.WriteLine($"Error converting {numeroidentista} to int value");
return;
}
2- Also for efficiency, do the conversions only once, you have repeated Convert.ToInt32(numeroidentista) 5 times . Just do it once and before your while loop.
3- And finally as pointed in the comment above, you have not initialized your inst array before using it.
4- As another tip, try to use $"" convention when forming a string using constants and variables. For example you can replace your first string with $"select COUNT(Id) from contas where posicao like 'Saúde' and convenio like '{convenio}'"

C# VFP OLEDB query throwing "Command contains unrecognized phrase/keyword"

I have a C# application intended to update one field in a table based on a value found in another table. Using the following:
listComm.CommandText = "update [c-disc] inner join [c-info] " +
"on [c-info].keys = [c-disc].cd_key set [c-disc].cd_distric = ? " +
"where [c-disc].cd_tax = ? and [c-info].ci_region = ?";
and in a foreach loop below it:
string region = line.Substring(0, 4).PadRight(14);
string taxable = "Y";
string district = line.Substring(5, 4).PadLeft(4);
listComm.Parameters.Add(new OleDbParameter("?", district));
listComm.Parameters.Add(new OleDbParameter("?", taxable));
listComm.Parameters.Add(new OleDbParameter("?", region));
try {
listComm.ExecuteNonQuery();
listComm.Parameters.Clear();
} catch (Exception x) {
setStatusText("fatal error: " + x.Message.ToString();
}
I'm getting "Command contains unrecognized phrase/keyword". Using the same query in MS Access works fine when I plug the appropriate values in place of the '?' placeholders. In Visual Studio, using breakpoints I see everything appears normal - the connection is open and the parameter values are as expected. I have another program that works similarly, but only against a single table. I can't for the life of me figure out what's wrong with this query.
Whoever designed that system, sounds to not have much knowledge about VFP. VFP is not totally ANSI SQL compatible and not only that have some naming rules. Your designer named the tables with dash in them? In documentation there are warnings as I remember. Anyway you can still go with that hoping, cd_key and cd_tax fields are only in 'c-disc' table (otherwise you need a little bit workaround).
using (OleDbConnection con = new OleDbConnection(#"Provider=VFPOLEDB;Data Source=c:\MyDataFolder"))
{
var sql = #"update [c-disc]
set cd_distric = ?
from [c-info] ci
WHERE ci.keys = cd_key AND
cd_tax = ? and ci.ci_region = ?";
var listComm = new OleDbCommand(sql, con);
listComm.Parameters.Add("dst", OleDbType.Char);
listComm.Parameters.Add("tx", OleDbType.Char);
listComm.Parameters.Add("reg", OleDbType.Char);
string taxable = "Y";
listComm.Parameters["tx"].Value = taxable; // constant?
con.Open();
// Loop here
// {
// These paddings do not smell good
string region = line.Substring(0, 4).PadRight(14);
string district = line.Substring(5, 4).PadLeft(4);
listComm.Parameters["dst"].Value = district;
listComm.Parameters["reg"].Value = region;
try
{
listComm.ExecuteNonQuery();
}
catch (Exception x)
{
setStatusText("fatal error: " + x.Message.ToString());
}
// loop ends here
// }
con.Close();
}

DataSet coming as Empty

I have a method called searchDB that search the database according to keyword typed by user.
I am storing the search results in DataSet. This method search in only one column.
public DataSet searchDB(string identifier)
{
DataSet dataSet = new DataSet();
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "*'";
//string sql = "SELECT [identifier] FROM [Category3]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "identifier");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
else
return dataSet;
}
The variable "identifier" gets value from the textbox.
Suppose, when i pass "windows" as value for variable, it should return 1 row.
But when i put breakpoint, it is hitting the if condition
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
and returning 0 rows.
Can anyone point out my mistake.
You seem to be using the SQL LIKE wrong (unless your identifier column really ends with an asterisk):
SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "*'
Like uses the % character for wildcard, instead of *, so try:
SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "%'
Edit: I didn't see that the question concerns MS Access, but the answer holds true still. See the following SO question: Why does a LIKE query in Access not return any records?
The Access Database Engine (Jet, ACE, whatever) has two ANSI Query Modes which each use different wildcard > characters for LIKE:
ANSI-89 Query Mode uses *
ANSI-92 Query Mode uses %
The LIKE filter should use % instead of * like here:
LIKE '" + identifier + "%'

InvalidCastException: Unable to cast object of type 'System.Decimal' to type 'System.String'

I am attempting to get the sale price from a table and put it into a text box. On my table the sale price is a Decimal variable, and of course the text box is string.. When I run this, there is an exception that is stopping it in my Data Access Layer.
Here is some code:
textSellPrice.Text = DAL.Util.getSellPrice(listItemsPricing.SelectedValue.ToString());
public static String getSellPrice(string item)
{
string sql = "SELECT Price FROM Item it INNER JOIN Customers cu
ON it.SalesRep = Cu.SalesRep WHERE CustomerID='"
+ HttpContext.Current.Session["SelectedCustomer"] +
"' AND ProductID='" + item + "'";
string dt = AdoUtil.GetDataColumn(sql);
return dt;
}
public static string GetDataColumn(string sqlQuery)
{
string result = String.Empty;
try
{
SqlCommand cmd = new SqlCommand(sqlQuery, GetACESConn());
if (cmd.Connection.State != ConnectionState.Open)
cmd.Connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
{
result = reader.GetString(0);
}
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
return result;
}
catch (Exception ex)
{
return result;
}
}
So is there something completely obvious that I am missing?
Thanks for any helpful insight to this, and if any other code could be of use, I can provide it. Thank you
You're selecting a price, which is presumably a decimal. So don't call reader.GetString(0) - call reader.GetDecimal(0) and store the result in a decimal variable. If you really want to convert everything into a string, just call GetValue(0).ToString().
While you're there, please fix this:
string sql = "SELECT Price FROM Item it INNER JOIN Customers cu ON it.SalesRep = Cu.SalesRep WHERE CustomerID='" + HttpContext.Current.Session["SelectedCustomer"] +
"' AND ProductID='" + item + "'";
This is just begging for a SQL Injection Attack. Don't put values directly into SQL like this. Instead, use parameterized SQL and specify the values for those parameters. See SqlCommand.Parameters for an example.
Next up, don't catch Exception, and don't return a value when an exception is thrown as if nothing had happened... you'll be masking errors for no reason.
CustomerId is declared as a numeric type in the database, but you are trying to read it as a string. If you must have your result as a string, you can either:
read it as a numeric type (say, a decimal) and convert to string in C#, or
change your SQL to cast it to varchar on the RDBMS side
On a side note, you should not bake parameter values into your queries to avoid Bobby Tables; you need to use parameterized queries instead.

Unexpected behavior when DELETEing from TABLE in SQL

I have done it before, but it's not working this time.
All I'm trying to do is delete an entry from a table, and as you can see, it is supposed to output "ok" if it succeeds, (and I have manually checked the querystring data and everything matches what its trying to delete, even all the conditions are also met), but it isn't deleting.
#{
var message = "";
try
{
var d = Database.Open("tgyytuyt");
var query = "DELETE FROM Cart WHERE OrderId = '" + Request.QueryString["Value"] + "' AND UserId = '" + Request.QueryString["SubValue"] + "' AND PartNumber = '" + Request.QueryString["Final"] + "'";
d.Execute(query);
message = "ok";
//Response.Redirect("~/OSM/Default.cshtml");
}
catch(Exception ex)
{
message = ex.Message;
}
}
<p>#message</p>
Is there something that I'm doing wrong that could be causing the item to not be deleted?
The most likely cause is, that there is no row in your database which meets the conditions of your where clause.
Check that first.
But without more information about the value of your querystring and your database setup its all guessing.
It might also be a trigger...
I don't know what your execute is doing, but you should be executing a non-query. You might want to check on that.

Categories

Resources