Error one or more parameters is required - c#

This is C# code and giving me an error that one or more parameters are required in the access database can anyone help me?...I am hanged due to this error!
Here's the code:
string date = textBox1.Text;
con = new OleDbConnection(cs);
con.Open();
String sql = "SELECT * From Sales where InvoiceDate = date ";
cmd = new OleDbCommand(sql, con);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;

First I recommend parsing that date to a DateTime as I hope your InvoiceDate is an actual date type in the DB. Second you need to use a parameter to pass in the value. Finally remove that ExecuteNonQuery. Also you should put disposable items into using statements so the connection will be closed properly.
DateTime date;
if(!DateTime.TryParse(textBox1.Text, out date))
{
//Do whatever you need to indicate a bad date.
}
using(var con = new OleDbConnection(cs))
{
con.Open();
String sql = "SELECT * From Sales where InvoiceDate = #date";
using(var cmd = new OleDbCommand(sql, con))
{
cmd.Parameters.Add("#date", /*Insert correct type here*/).Value = date;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
}
}

First flaw : You didn't mention what cs is(i mean show us the connection string) but not much of a big issue as it is not throwing the error.
Second flaw : InvoiceDate = date , here date is neither a value nor a variable.
To use it as a variable
...InvoiceDate ='" + date + "'"
To use it as direct value
...InvoiceDate ='date'"
Third Flaw : cmd.ExecuteNonQuery , it is unnecessary.
Fourth flaw : Well, i shouldn't call it a flaw,rather a bit of knowledge sharing : You can create a separate DataAdapter and then use it to populate your table :
OleDbDataAdapter ada = new OleDbDataAdapter(cmd);
ada.Fill(mydatatable);
Biggest flaw : Sql-Injection , please don't make it easy for attackers.Rather use parameters:
"SELECT * From Sales where InvoiceDate=#date"
cmd.Parameters.Add("#date", OleDbType.Varchar).Vale = dateStringHere ///change data-type from varchar as required

Related

Data type mismatch in criteria expression ms-access c#

I have MS Access database have table which contains below data.
TradeDate TradeType TicketNo PassengerName
11-Feb-19 SALE 1234 ABC
12-Feb-19 PURCHASE 0345 XYZ
I want to get data between two dates with TradeType, below is my code from C#
public static DataTable GetSale(DateTime FromDate, DateTime ToDate, string TradeType)
{
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(Utility.GetConnectionString());
OleDbCommand cmd = new OleDbCommand("SELECT A.AgencyName, T.TradeDate, T.InvoiceNo, T.TicketNo, T.PassengerName, T.FatherName, T.TicketAmount, T.RefundAmount FROM Agencies AS A, Trade AS T WHERE T.Account_ID=A.Account_ID and T.TradeType=#TradeType And T.TradeDate>=#FromDate And T.TradeDate<#ToDate", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#FromDate", FromDate);
cmd.Parameters.AddWithValue("#ToDate", ToDate);
cmd.Parameters.AddWithValue("#TradeType", TradeType);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
con.Open();
da.Fill(dt);
con.Close();
}
while executing my code
Data type mismatch in criteria expression.
Exception is thrown. What am I doing wrong?
please use ...Parameters.Add(...) instead of AddWithValue.
Without explicitly providing the type as in command.Parameters.Add("#param", SqlDbType.Int);, it will try to implicitly convert the input to what it is expecting and it fails.
First thing you should know is parameters in OleDbCommand processed from order of their definition, you need to define parameters in same order as they're appeared in query (OLE DB doesn't support named parameters).
Second, use Add() instead of AddWithValue() by specifying OleDbType for each parameter, you can see the list of types here.
Here is an example of correct setup:
OleDbConnection con = new OleDbConnection(Utility.GetConnectionString());
OleDbCommand cmd = new OleDbCommand(#"SELECT A.AgencyName, T.TradeDate, T.InvoiceNo, T.TicketNo, T.PassengerName, T.FatherName, T.TicketAmount, T.RefundAmount
FROM Agencies AS A, Trade AS T
WHERE T.Account_ID=A.Account_ID
and T.TradeType = #TradeType And T.TradeDate >= #FromDate And T.TradeDate < #ToDate", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#TradeType", OleDbType.VarWChar).Value = TradeType;
cmd.Parameters.Add("#FromDate", OleDbType.Date).Value = FromDate;
cmd.Parameters.Add("#ToDate", OleDbType.Date).Value = ToDate;

got error on datetime while using JsonServices in asp.net and android

We are doing an app which uses jsonservice(webservice/RESTfull webservice) for backend datadase proccess and andriod as front end..
public DataTable retrv(string id)
{
check();
int ID = Convert.ToInt32(id.ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from RECVSSMS where Refid='" + ID + "'";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
While using this code using jsonservice from Android Studio we got all the records in exact format except the Date_Time.
we got records like this :
I/System.out: ######################{"Value":[{"Date_time":"2016-04-22T02:01:15","status":"1","Message":"test messag reply automatic","FromID":"+919566003138","Refid":24}],"Successful":true}
here is the error clearly : Date_time":"2016-04-22T02:01:15"
An alphabet 'T' appears and incorrect date format
This is database fields:
Refid int
FromID varchar(13)
Message varchar(60)
status varchar(5)
Date_Time datetime
It's not an error it's one of the date time formats sql provide please use the below formatting code to get the desired date
http://www.w3schools.com/sql/func_convert.asp

Must declare scalar variable while displaying data in datagridview

DateTime startSchedule = dateTimePicker1.Value.Date;
DateTime endSchedule = dateTimePicker2.Value.Date;
cn.Open();
string display = "select * from Issue where Date_Borrowed >= #startSchedule and Date_Borrowed < #endSchedule";
SqlCommand cmd = new SqlCommand(display,cn);
cmd.Parameters.AddWithValue("#startSchedule", startSchedule);
cmd.Parameters.AddWithValue("#endSchedule", endSchedule);
DataSet ds = new DataSet();
SqlDataAdapter adapt = new SqlDataAdapter(display, cn);
adapt.Fill(ds, "Issue");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Issue";
cn.Close();
I have two dateTimePickers and Im trying to display the data i have in my database that is within those two date.
I'm not %100 sure but AddWithValue might be the reason in here. I would suggest to add your parameters with specifing their types.
cmd.Parameters.Add("#startSchedule", SqlDbType.Date).Value = startSchedule;
cmd.Parameters.Add("#endSchedule", SqlDbType.Date).Value = endSchedule;
Also use using statement to dispose your connection, command and adapter automatically instead of calling Close or Dispose methods manually.

Specified cast is not valid

I have an application that get a datetime value from the database but it give me this error
Specified cast is not valid
here is the code
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Golden_RoseConnectionString"].ConnectionString);
con.Open();
String sel3 = "select Booking_Date from booking where Booking_ID='" + Booking_Id + "'";
SqlCommand cmd3 = new SqlCommand(sel2, con);
SqlDataReader n3 = cmd3.ExecuteReader();
n3.Read();
DateTime Booking_Date = (DateTime)n3.GetSqlDateTime(0);
con.Close();
How can I solve this problem?
You should use:
var Date = Convert.ToDateTime(n3["YOUR_DATE_COLUMN"]);
an sql date is not a .Net DateTime object.
GetSqlDateTime does not do a convertion - see MSDN.
It must be converted - see the SO question as an example

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value

I have a WPF application. date is my table and its two columns are employeename (varchar(10)) and date (datetime)
My code is:
Sqlconncetion con = new Sqlconnection("my database connection ");
SqlCommand cmd = new SqlCommand("insert into date values('"+textBox1.Text+"','"+datePicker1.Text+"')", con);
con.Open();
int n = cmd.ExecuteNonQuery();
if (n > 0)
{
MessageBox.Show("insert");
}
Actually my WPF datepicker formats inputs as "dd/mm/yyyy" and SQL Server table accept date format mm/dd/yyyy. How can I change my SQL Server datetime datatype date format? please give solution by code in c#..
My task is to display all name and birth date. My condition is basic but at time of date selection and button enter, I get exception. My code is
SqlConnection con = new SqlConnection("my connection ");
SqlDataAdapter da = new SqlDataAdapter("select name,date from date where date between'"+ Convert.ToDateTime( datePicker2.SelectedDate)+"' and '"+ Convert.ToDateTime( datePicker3.SelectedDate)+"'",con);
DataSet ds = new DataSet();
da.Fill(ds, "entry");
da.Dispose();
dataGrid1.DataContext = ds.Tables["entry"].DefaultView;
plz help me solve code error and write correct code . this is a WPF application.
Use SqlParameters to pass your values to database. It gives you type safety, performance, and prevents SQL injection. Also use using statement to guarantee database connection will be closed:
var cmdText = "INSERT INTO date VALUES(#name, #date)";
using(var con = new SqlConnection(conString))
using(var cmd = new SqlCommand(cmdText, con)) {
cmd.Parameters.Add("#name", textBox1.Text);
cmd.Parameters.Add("#date", datePicker1.SelectedDate);
con.Open();
int n = cmd.ExecuteNonQuery();
//...
}

Categories

Resources