Get data from database using month - c#

try
{
conn5.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conn5;
string query = "select * from OrderDataListTable WHERE MONTH(`DATETIME`) = dateString";
command.CommandText = query;
reader = command.ExecuteReader();
What is the right syntax to compare my input month to the database?
String dateString = Convert.ToString(textBox2.Text);
DateTime month = Convert.ToDateTime(dateString + "01, 1990").Month;

You would use something like this with properly formatted string expressions for the dates of the interval:
DateTime monthDate = DateTime.Parse(textBox2.Text);
string startDate = new DateTime(monthDate.Year, monthDate.Month, 1).ToString("yyyy'/'MM'/'dd");
string endDate = new DateTime(monthDate.Year, monthDate.Month + 1, 1).AddDays(-1).ToString("yyyy'/'MM'/'dd");
and then:
string query = "select * from OrderDataListTable where [DATETIME] between #" + startDate + "# and #" + endDate + "#";

Related

Bringing Specific Date Record in MS access using C#

I want to bring a records of commission on specific date. Here is my code;
globalxx = 0;
string month1 = dateTimePicker2.Value.Month.ToString();
string day1 = dateTimePicker2.Value.Day.ToString();
string year1 = dateTimePicker2.Value.Year.ToString();
string s2 = "#" + month1 + "/" + day1 + "/" + year1 + "#";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(xi))
{
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission='" + s2 + "'", conn);
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#DateCommission", s2)
});
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
dataGridView2.DataSource = results;
But the problem is it gives error at
adapter.Fill(results);
saying: "OleDB Excpetion has been handeled Data type mismatch in criteria expression."
I Need help.
My MS Access Schema is:
DateCommission: Date Time
DriverName: TEXT
DriveVehicleNumber: TEXT
CommissionedPrice: NUMBER
I am not got at parameter.
Here is the front end of c#;
Front End
Handle your date as that, and then concatenate a formatted string expression in the SQL:
string textDate = dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd");
string s2 = "#" + textDate + "#";
and then:
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission = " + s2 + "", conn);
Or (preferred) use a parameter of data type DateTime which you pass Value of the datepicker directly.

Insert mysql datetime

I keep on having this error "Incorrect datetime value '2/1/16 7:22:00 AM'. I am sending a datetime value to a datetime data type column in mysql.
This is my code :
String AMTime =(AMHour.Text + ':' + AMMinute.Text).ToString();
am = Convert.ToDateTime(AMTime);
// string am = AMTimeConvert.ToString("HH:mm:ss");
String NNTime = (NNHour.Text + ':' + NNHour.Text).ToString();
nn = Convert.ToDateTime(NNTime);
// string nn = NNTimeConvert.ToString("HH:mm:ss");
String PMTime = (PMHour.Text + ':' + PMMinute.Text).ToString();
pm = Convert.ToDateTime(PMTime);
// string pm = PMTimeConvert.ToString("HH:mm:ss");
if (Generic != null || Brand != null || ContainerNum != "" || status != "")
{
result = database.AddMedicinePrescription(PrescribedDays,Dosage,numprescribed,NumofIntake,am,nn,pm);
}
This is the code that is to connect to my db
public bool AddMedicinePrescription(int PrescribedDays, int Dosage, int numprescribed, int NumofIntake, DateTime am, DateTime nn, DateTime pm)
{
sqlstring = "INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)" + "VALUE (" + PrescribedDays + ", " + numprescribed + ", " + Dosage + ", " + NumofIntake + ", '"+ am +"', '"+ nn +"', '"+ pm +"' ) ";
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(sqlstring, connect);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
connect.Close();
return true;
}
catch (Exception error)
{
MessageBox.Show("Warning 2: " + error.Message);
return false;
}
Because you try to add your DateTime values as a character with single quotes like '"+ am +"'
You need to delete all single quotes for your DateTime values.
But more important, stop the string concatenation when you build your commands. You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also you need ExecuteNonQuery instead of using a MySqlDataAdapter since INSERT statement does not return any data. It just inserts your value.
using(var connect = new MySqlConnection(conString))
using(var cmd = connect.CreateCommand())
{
cmd.CommandText = #"INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)
VALUE (#PrescribedDays, #numprescribed, #Dosage, #NumofIntake, #am, #nn, #pm)";
// Add your parameters with specify their types and size.
connect.Open();
cmd.ExecuteNonQuery();
}
Also you might need to read: Bad habits to kick : choosing the wrong data type

How to find today's data from database from two different dates?

I have a database ShiftChange, and the fields are
Fromdate='09/11/2014', Todate='11/11/2014',Shift='MG' and Month='11'(dd/MM/YYYY format)
Fromdate='11/11/2014', Todate='15/11/2014',Shift='AF' and Month='11
I want to find today's shift from these table. I tried like this,
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("dd/MM/yyyy");//system date converted to given format
int month = DateTime.Now.Month;
string str = "Select Min(Fromdate), Max(Todate) From ShiftChange where Month='" + month + "'";
SqlDataReader dr = conn.query(str);
if (dr.Read())
{
string mindate = dr[0].ToString();
string maxdate = dr[1].ToString();
string str3 = "select Shift from ShiftChange where '" + s_today + "' >= '" + mindate + "' and '" + s_today + "' <= '" + maxdate + "' and Month='"+month+"'";//checks current shift type of selected date.
SqlDataReader dr3 = conn.query(str3);
if (dr3.Read())
{
string shiftid = dr3[0].ToString();
}
Here connection is my connection class and query is my (sqldatareader dr) method.When I run this query I am getting shiftName 'MG' but actually the shiftName correspondent to today's date is 'AF' but it not getting. I hope it is my query's issue. Please show me the error
First of all you should make your query parameterized or you can prepare sql stored procedure and use that stored procedure in your code. I am giving you sql code for stored procedure here.
declare #month varchar(50) = '11'
declare #mindate varchar(50)
declare #maxdate varchar(50)
declare #date varchar(50)
select #mindate=min(fromdate),#maxdate = max(todate)
from ShiftChange Where Month = #month
select TOP 1 Shift From ShiftChange
WHERE #date>= fromdate and todate<=#date
and month = #month
order by todate desc
Btw, it's always better to use datatype date or datetime when dealing with dates.
I solved this issue with #Mukund's help. I applied his code in my project like this,
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("dd/MM/yyyy");
int month = DateTime.Now.Month;
string str = "Select Min(Fromdate), Max(Todate) From ShiftChange where Month='" + month + "'";
SqlDataReader dr = conn.query(str);
if (dr.Read())
{
string mindate = dr[0].ToString();
string maxdate = dr[1].ToString();
string str3 = "select TOP 1 Shift From ShiftChange WHERE '"+s_today+"'>=Fromdate and Todate>='"+s_today+"' and month = '"+month+"' order by Todate desc";
SqlDataReader dr3=conn.query(str3);
if(dr3.Read())
{
string shift = dr3[0].ToString();
}

how to insert a date from textbox to database

please help me to insert a date from a text box in dd-mm-yyyy format to sql server.
my code is as follows:-
int prio = Convert.ToInt32(Priority.Text);
string stdate = planstart.Text;
string endate= planend.Text;
string actst = actualstart.Text;
string acten = actualend.Text;
SqlConnection myconnection = new SqlConnection(constring);
SqlCommand mycommand = new SqlCommand();
DataSet mydataset = new DataSet();
SqlDataAdapter mydataadapter = new SqlDataAdapter();
myconnection.Open();
mycommand.Connection = myconnection;
mycommand.CommandText = " insert into project_status.dbo.Project_Status_Report values('" + projectcode.Text + "','" + projectname.Text + "',(select P_Code from project_status.dbo.Project_Type where Project_Type = '" + projecttype.Text + "')," + prio + ",'" + stdate + "','" + endate + "','" + actst + "','" + acten + "','" + currentstatus.Text + "','" + remark.Text + "','no');";
mycommand.CommandType = CommandType.Text;
mycommand.ExecuteNonQuery();
and it is throwing an exception saying:-
Conversion failed when converting date and/or time from character string.
You need to convert data according to you sql server formate that way you can resolve issue ..
Try
String UrDate = "27/12/2011";
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime validDate= Convert.ToDateTime(toDate, dateInfo);
or
Format String For Dates
// String to DateTime
String MyString;
MyString = "1999-09-01 21:34 PM";
//MyString = "1999-09-01 21:34 p.m."; //Depends on your regional settings
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
null);
Make use of Paramerize query to avoid SQL INJECTION...make code less error pron
Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query
Just a word of caution - you need to sanitize that query to prevent SQL injection attacks. Consider using parameterised queries. Read up about it, it's not really the scope of this answer.
You should create strongly typed DateTime objects first and then format them the way you need to insert. Consider the following modification to your code:
string stdate = DateTime.Parse(planstart.Text).ToString();
string endate = DateTime.Parse(planend.Text).ToString();
string actst = DateTime.Parse(actualstart.Text).ToString();
string acten = DateTime.Parse(actualend.Text).ToString();
EDIT
I removed the string parameter from the ToString() so you can get a valid DateTime string that's usable by SQL Server.
con.Open();
string query = "insert_demo";
/* date fromat Stored*/
TextBox2.Text = DateTime.Now.ToLongDateString();
SqlCommand com = new SqlCommand(query, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", TextBox1.Text.ToString());
com.Parameters.AddWithValue("#Date", TextBox2.Text.ToString());
com.ExecuteNonQuery();

Incorrect syntax near '00'

I am new in asp & sql server. I have a problem in sql query.
string obal ;
decimal _obalss = 0;
decimal obalss = 0;
sconnection c = new sconnection();
string cus_id = Session["cusid"].ToString();
DateTime maxdate = DateTime.Parse(fromdt.Text, new System.Globalization.CultureInfo("en-US"));
string mdate = maxdate.ToString();
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
SqlDataReader dr = c.reader(query_sl);
if (dr.Read())
{
decimal.TryParse(dr["amount"].ToString(), out _obalss);
obalss = _obalss;
}
else
{
obalss = 0;
}
dr.Close();
dr.Dispose();
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
maxdate is a date, you have to put it in single quotes. Even better you should use parameterized SQL queries otherwise you are vulnerable to SQL injection attacks. How about something like this:
string query_sl = "select sum(amount) as amount from sale where cusid = #CUSID and invdate < #MAXDATE group by cusid";
using(SqlCommand cmd = new SqlCommand(query_sl, c))
{
cmd.Parameters.Add(new SqlParameter("#CUSID", SqlDbType.Int)).Value = cus_id;
cmd.Parameters.Add(new SqlParameter("#MAXDATE", SqlDbType.DateTime)).Value = maxdate;
...
}
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < '" + maxdate + "' group by cusid";
Notice the single quotes around maxdate...

Categories