I am getting a System.Data.SqlClient.SqlException with additional information of an Invalid column name Jun on Fill function while I am entering 19-jun-2016 from the datetimePicker and here is a Jun is a month but it taking it as a column.
ReportForm.cs
public void MakeDailyReport(string givenDate, DataGridView view)
{
con.Open();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
DateTime dateObject = (DateTime)cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject.ToShortDateString());
string givenDateString = Convert.ToString(givenDate);
if (dateObjectstring == givenDateString)
{
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
Don't use string concatenation to build your query but sql parameters with the correct type. That will also prevent you from sql injection and other possible issues (like this one).
adapt = new SqlDataAdapter("SELECT [Date] FROM FinalSales where [Date] = #givenDate", con);
var dateParameter = adapt.SelectCommand.Parameters.Add("#givenDate", SqlDbType.DateTime);
dateParameter.Value = dateTimePicker.Value.Date; // not string but the correct type DateTime
Note that i've also used dateTimePicker.Value.Date to ignore the time portion.
Related
This my code where my passing dates and I want to display the data from the table as its from sql to view in ASP.NET MVC 5. And that two dates are also comes from view means after selecting this dates I have to pass it into the parameter in stored procedure
public DataTable Get_Availability(string ID = "")
{
string aDate = "03/03/2017";
string dDate = "20/03/2017";
DateTime oDate = Convert.ToDateTime(aDate);
DateTime uDate = Convert.ToDateTime(dDate);
queryString = "FO.USP_Check_AvailabilityOFRoom";
try
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand(queryString, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(New SqlParameter("#Date_Of_Birth",Data.SqlDbType.DateTime));
cmd.Parameters("#Date_Of_Birth").Value = DOB
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
return ds.Tables[0];
}
}
}
}
catch
{
return null;
}
return null;
}
Try this
cmd.Parameters.Add("#parametername", date);
#parametername is parameter in you SP.
date is your date variable.
i have a web service in which training number is assigning as per my database
there is a line
dates + "1"; this lines add 1 in date
like 27012017 will become 270120171
then i convert this into int64
newid = Convert.ToInt64(dates);
but now i want to add trainer id in this
so i updated my line with this
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
the error is coming input string is not in correct format,
i know this is because of the addition of +"-"+
but i want to store the data in this format only
and my whole portion look like
DateTime dt = DateTime.Now;
string dates = dt.ToString();
dates = dates.Replace("-", "");
dates = dates.Substring(0, 8);
SqlCommand cmdbill = new SqlCommand("select top 1 * from listmybill where bill_id like #trid order by bill_id desc", con);
con.Open();
cmdbill.Parameters.AddWithValue("#trid", "%" + dates + "%");
SqlDataReader dr = cmdbill.ExecuteReader();
while (dr.Read())
{
value = dr["bill_id"].ToString();
}
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdbill);
DataTable dat = new DataTable();
da.Fill(dat);
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
else
{
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
}
con.Close();
what should i do here,
i want to enter the data like 001-270120171
and if i convert toInt64 into string,
there can be problem when a row found in the table
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
what i need to do now?
i want to store this into my database
I hardly think you will be doing mathematical calculations on this training number string. I suggest that you convert the int in your database into a varchar using alter statement. Then you you will be able to store the training number in whichever format you like.
You can change new id to string and do the following
if (dat.Rows.Count > 0)
{
newid = Convert.ToString(Convert.ToInt64(value)+1);
}
else
{
newid="00"+trainerid +"-"+ dates + "1";
}
I am trying show some data from a database to a combobox based on another combobox selection with this code:
private void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dt = new DataSet();
try
{
DateTime startDate = Convert.ToDateTime(metroLabel8.Text);
DateTime endDate = Convert.ToDateTime(metroLabel9.Text);
// Make sql readable
string sql =
#"Select [LedId],[LedName] from [Ledger] where Date >= #prmStartDate and Date <= #prmEndDate";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
con.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
VoucherLedgerName_combo.DisplayMember = "LedName";
VoucherLedgerName_combo.ValueMember = "LedId";
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
}
}
catch(Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
But i am getting nothing in the second combobox, and I am sure that there is data in the database table Ledger. Can any one please help me to find the issue?
change your SQL statement as below(Date is reserved keyword)
string sql =
#"Select [LedId],[LedName] from [Ledger] where [Date] >= #prmStartDate and [Date] <= #prmEndDate";
You need to give table name when you fill dataset since you are using the name when you set data source
da.Fill(dt, "Ledger");
or set the data source as below
VoucherLedgerName_combo.DataSource = dt.Tables[0];
DataRow dr = dt.NewRow();
dr["Ledger"] = "--Select All--";
dt.Rows.InsertAt(dr, 0);
You can change from
da.Fill(dt);
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
to
da.Fill(dt, "Ledger");
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"].DefaultView;
else
VoucherLedgerName_combo.DataSource = dt.Tables[0].DefaultView;
or
VoucherLedgerName_combo.DataSource = dt;
I am trying to get data in gridview on the basis of the date that is entered in dateTimePicker. But, I am getting null reference runtime error on if condition where I have used equals function to compare two strings.
ReportFrom.cs
private void button1_Click(object sender, EventArgs e)
{
string date = dateTimePicker.Value.ToShortDateString();
reportLayer.MakeDailyReport(date, dataGridViewReport);
}
ReportLayer.cs
private SqlConnection con = new SqlConnection("Data Source=CHAMP-PC;Initial Catalog=ProcessSale;Integrated Security=True");
private SqlCommand cmd;
private SqlDataAdapter adapt;
public void MakeDailyReport(string givenDate, DataGridView view)
{
try
{
con.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
object dateObject = cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject);
string givenDateString = Convert.ToString(givenDate);
// string DBdate = dateObject.ToString();
if (dateObject.Equals(givenDate))
{
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
con.Close();
}
}
Have a look here:
Handling ExecuteScalar() when no results are returned
Additionally: Be careful with the call to Equals(). Currently you are comparing
two strings. One with a ShortDate value One with the default ToString().
Event if the dates are equal, this might return false.
A better solution would be handling both values as DateTime and use the == operator.
Thomas
I'm having trouble updating a mySQL database with a datatable. I can do it with an INSERT statement, but the table fails the assignment when I insert a row with the error "Couldn't store <...> in date Column. I have millions of records to insert and I thought this way might be faster. I actually don't care about the time, just the date.
MySqlConnection con = new MySqlConnection();
con.ConnectionString = string.Format(#"server={0};userid={1};password={2};database={3};AllowZeroDatetime=True", srvr, user, pass, db);
MySqlCommand cmnd = new MySqlCommand();
cmnd.Connection = con;
con.Open();
cmnd.CommandText = "DROP TABLE IF EXISTS dateTest";
cmnd.ExecuteNonQuery();
cmnd.CommandText = "CREATE TABLE dateTest (date DATE, dateTime DATETIME)";
cmnd.ExecuteNonQuery();
string myDate = "2014-04-19";
string myDateTime = "2014-04-20 00:00:00";
//this code works
cmnd.CommandText = string.Format("INSERT INTO dateTest(date, dateTime) VALUES('{0}', '{1}')", myDate, myDateTime);
cmnd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * from dateTest", con);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
DataTable tbl = new DataTable();
da.Fill(tbl);
foreach (DataRow row1 in tbl.Rows)
{
Debug.WriteLine(string.Format("{0} : {1}", row1["date"], row1["dateTime"]));
//returns: 4/19/2014 : 4/20/2014 12:00:00 AM
}
DataRow row2 = tbl.NewRow();
row2["date"] = myDate; //Errors here: Couldn't store <2014-04-19> in date Column. Expected type is MySqlDateTime.
row2["dateTime"] = myDateTime; //Also errors here: Couldn't store <2014-04-20 00:00:00> in dateTime Column. Expected type is MySqlDateTime.
tbl.Rows.Add(row2);
da.Update(tbl);
this is my first time trying to answer a question. Hope this help.
I think you have to convert the date to DateTime first before you can store it in mysql.
string myDateTime = "2014-04-20 00:00:00";
DateTime myDateTimeValue = DateTime.Parse(myDateTime);
Then
row2["dateTime"] = myDateTimeValue;
I have not tried it yet. Hope it works