ASP.Net don't match the Access Date/Time Column - c#

I'm trying to sort for today. I am giving match error while I am comparing.
OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dragonfly\\Documents\\Visual Studio 2013\\WebSites\\WebSite2\\App_Data\\calismagunluk.mdb");
OleDbDataReader oku;
OleDbCommand sorgu =new OleDbCommand();
DateTime bugun = DateTime.Now.Date;
sorgu.CommandText = "select * from calisan where kulID=" + sesionKulId +
" AND gun='" + bugun + "' ";
oku = sorgu.ExecuteReader();//I give error in here
if (oku.HasRows) {
Repeater1.DataSource = oku;
Repeater1.DataBind();
oku.Dispose();}
else{
Repeater1.Visible = false;
repeaterBos.Text = "Bugün Hiç Çalışma Yapmamışsınız...";
oku.Dispose();
}
I am getting this error: "Data type mismatch in criteria expression".
If I change the db column to Text, it is working. But I don't want it this way. How should I follow the way?

You can bypass the format problem and let the command work the format by itself by using parameters:
OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dragonfly\\Documents\\Visual Studio 2013\\WebSites\\WebSite2\\App_Data\\calismagunluk.mdb");
OleDbDataReader oku;
OleDbCommand sorgu =new OleDbCommand();
DateTime bugun = DateTime.Now.Date;
sorgu.CommandText = "select * from calisan where kulID=#ID AND gun=#date";
sorgu.Parameters.Add("#ID", OleDbType.Integer).Value = susionKulId;
sorgu.Parameters.Add("#date", OleDbType.DBTimeStamp).Value = bugun;

Related

How to search between 2 dates on access database vs?

I'm trying this code but it shows an error on da.Fill(dt)
No value given for one or more required parameters.
Why does it show that error? I clearly check all names of databases and tables and fields, they all are correct and I'm using date/time field for datetime.
Can you help me with this?
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb";
OleDbConnection ccc = new OleDbConnection(conn);
ccc.Open();
string css = "SELECT * from tbl3 Where dateitem between '" + dateTimePicker1.Value.ToString() + "%' AND '" + dateTimePicker2.Value.ToString()+"%'";
OleDbCommand non = new OleDbCommand(css, ccc);
OleDbDataAdapter da = new OleDbDataAdapter(non);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
As others have mentioned you should use the parameters instead of hard coding the values.
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb"))
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
var param1 = new OleDbParameter("#DateTimePicker1", OleDbType.DBDate); //you may have to play with different types
param1.Value = dateTimePicker1.Value;
cmd.Parameters.Add(param1);
var param2 = new OleDbParameter("#DateTimePicker2", OleDbType.DBDate);
param2.Value = dateTimePicker2.Value;
cmd.Parameters.Add(param2);
cmd.CommandText = "SELECT * from tbl3 Where datetime >= #DateTimePicker1 and datetime <= #DateTimePicker2";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
}
}

Select SQL using c# error can someone guide this one

What I'm missing?
I've got error:
Sqlexception was unhandled by usercode
SqlConnection con = new SqlConnection(MyConnectionString);
SqlCommand objCmd;
con.Open();
SqlDataReader dtReader;
String strSQL;
strSQL = "SELECT * FROM " + DropDownList1.SelectedValue + "'";
objCmd = new SqlCommand(strSQL, con);
dtReader = objCmd.ExecuteReader();
//*** BindData to GridView ***//
GridView3.DataSource = dtReader;
GridView3.DataBind();
dtReader.Close();
dtReader = null;
Try this ,
strSQL = "SELECT * FROM " + DropDownList1.SelectedValue;
ie., just remove ' from the query string.
Then add the following code at the end.
GridView3.DataSource = dtReader;
GridView3.DataSourceID = String.Empty;
GridView3.DataBind();
this code works now
SqlConnection con = new SqlConnection(MyConnectionString);
SqlCommand objCmd;
con.Open();
SqlDataReader dtReader;
String strSQL;
strSQL = "SELECT * FROM " + DropDownList1.SelectedValue ;
objCmd = new SqlCommand(strSQL, con);
dtReader = objCmd.ExecuteReader();
GridView3.DataSource = dtReader;
GridView3.DataSourceID = String.Empty;
GridView3.DataBind();
dtReader.Close();
dtReader = null;

Conversion failed when converting date and/or time from character string 4

Not certain what I need to do here ... I have a SQL statement in a SqlCommand that works:
SqlCommand cmd = new SqlCommand("select * from fb_results where fb_date between '20130501' and '20130629' and fb_response = 'Yes' Order by fb_date, fb_login", conn);
Now I want to substitute a query string parameter for the hard coded date.
Here is my code:
string arg1 = Request.QueryString["date1"];
string arg2 = Request.QueryString["date2"];
DateTime dt1 = Convert.ToDateTime(arg1);
DateTime dt2 = Convert.ToDateTime(arg2);
string cvt1 = "'"+dt1.Year.ToString() + dt1.Month.ToString() + dt1.Day.ToString()+"'";
string cvt2 = "'"+dt2.Year.ToString() + dt2.Month.ToString() + dt2.Day.ToString()+"'";
string qry = "select * from fb_results where fb_date between " + cvt1 + " and " + cvt2;
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("feedback"));
SqlCommand cmd = new SqlCommand(qry, conn);
//SqlCommand cmd = new SqlCommand("select * from fb_results where fb_date between '20130501' and '20130629' and fb_response = 'Yes' Order by fb_date, fb_login", conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
I am getting an error
Conversion failed when converting date and/or time from character string.
What can I do to correct this? Thank you for any assistance.
Regards,
Try using parameterized queries and DateTime.TryParse.
DateTime dt1;
DateTime dt2;
if(!DateTime.TryParse(arg1, out dt1) && !DateTime.TryParse(arg2, out dt2))
{
// Handle error
}
const string query = "select * from fb_results where fb_date between #from and #to";
var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#from", dt1);
command.Parameters.AddWithValue("#to", dt2);
Convert.ToDateTime(string) expects a format supported by the current culture. If you're using yyyyMMdd, this is most likely NOT a supported format. See this link for expected formats.
I would like to add to this and say you should definitely use a parameterised query as suggested by Romoku.
dt1.Month.ToString()
If the month number is 1 digit, and you concatenate, you could end up with a date like this:
2013624 (notice that you need 06, not just 6).
Instead you could try:
(dt1.Year * 10000 + dt1.Month * 100 + dt1.Day).ToString()
You haven't taken into account the need for zero padding on the dates. The code to construct cvt1 and cvt2 should look something like this:
string cvt1 = "'"+dt1.Year.ToString("0000") + dt1.Month.ToString("00") + dt1.Day.ToString("00")+"'";
string cvt2 = "'"+dt2.Year.ToString("0000") + dt2.Month.ToString("00") + dt2.Day.ToString("00")+"'";

query string data type mismatch

I'm using OLEDB to query an excel file using date time picker but I keep getting a Data type mismatch in cireria expression error.
The format in excel for the date is "6/08/2012 10:00"
DateTime time = dateTimePicker1.Value;
MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time + "')", MyConnection);
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
bindingSource1 = new BindingSource();
bindingSource1.DataSource = DtSet;
bindingSource1.DataMember = DtSet.Tables[0].TableName;
dataGridView1.DataSource = bindingSource1;
MyConnection.Close();
You are passing time to the query as a string, so you could ToString() it to make it work:
MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time.ToString("%M/dd/yyyy HH:mm") + "')", MyConnection);
But you really should make it a parameter. Plus, it's safer that way.
using (OleDbConnection connection = new OleDbConnection(yourConnectionString))
{
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [CR$] where [Req Start Date] >= ?", connection);
adapter.SelectCommand.Parameters.Add("#p1", OleDbType.Date);
adapter.SelectCommand.Parameters["#p1"].Value = time;
try
{
connection.Open();
adapter.Fill(DtSet);
}
catch (Exception ex)
{
//handle error
}
}
Find out more: OleDbParameter Class
Create an OleDbCommand and pass the value in as a parameter. Then use the Command as a parameter for the OleDbAdapter constructor...
string queryString = "select * from [CR$] where ([Req Start Date] >= ?)";
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.Add("#p1", OleDbType.DateTime).Value = time;
MyCommand = new OleDbDataAdapter(queryString, MyConnection);

C# How can i update some column datetime in datagridview to database

i need update some column in datagridview to database. but don't update to database.
step one: i select datetime from datetimepicker.
step two: show datetime on datagridview.
step tree: i need update/edit on datagridview to database.
Display on Datagridview.
EmpNo fName ChkDate ChkIn ChkOut
00001 Al 01/10/2012 08:02 17:04
00002 Bik 01/10/2012 07:43 18:35
i need update fields "ChkIn" to database.
Code
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),'" + dgvShow.Rows[i].Cells[3].Value + "',102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = '" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "' and [filesTA].EmpNo = '" + dgvShow.Rows[i].Cells[0].Value + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds;
da.Update(ds);
}
}
Error: Update unable to find TableMapping['Table'] or DataTable 'Table'.
I try other code:
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [filesTA]", appConn);
adapter.UpdateCommand = new SqlCommand("UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo", Conn);
adapter.UpdateCommand.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn");
adapter.UpdateCommand.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate");
adapter.UpdateCommand.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo");
DataSet ds = new DataSet();
adapter.Fill(ds);
dgvShow.DataSource = ds;
adapter.Update(ds);
this code not save to database.
Thanks for your time. :D
Type Database:
ChkIn and ChkDate Type DateTime,EmpNo Type NUMERIC
I try
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
using (Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA]" +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')" +
"FROM [WebSP].[dbo].[filesTA]" +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.DateTime, 10, "ChkIn").Value = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value).ToString();
cmd.Parameters.Add("#cDate", SqlDbType.DateTime, 10, "ChkDate").Value = Convert.ToDateTime(dateTimePicker.Value.ToString()).ToString();
cmd.Parameters.Add("#eNo", SqlDbType.Decimal, 10, "EmpNo").Value = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value).ToString();
cmd.ExecuteNonQuery();
}
}
}
Error: Conversion failed when converting date and/or time from character string. T__T
You could try to get rid of the SqlDataAdapter using directly a SqlCommand
Using(Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA] " +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':') " +
"FROM [WebSP].[dbo].[filesTA] " +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn").Value =
dgvShow.Rows[i].Cells[3].Value;
cmd.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate").Value =
dateTimePicker.Value.ToString("yyyy-MM-dd") ;
cmd.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo").Value =
dgvShow.Rows[i].Cells[0].Value ;
cmd.ExecuteNonQuery();
}
Of course, when using parameters, we need to set their values before running the command.
However I really don't understand well the code to update the ChkIn field. That field (according to the Parameter type) is a nvarchar, then why don't you try to format your #cIn value directly in code and avoid the use of Sql Server Replace and Convert functions? Also the 102 is a Date Style. It is used to format Date expressions as strings with the yy.mm.dddd pattern, but you have a string that contains only time info.
For example
After your last edit - changed to this
DateTime chkIN = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value);
DateTime chkDate = Convert.ToDateTime(dateTimePicker.Value.ToString("yyyy-MM-dd"));
decimal empNo = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value) ;
cmd.Parameters.Add("#cIn", SqlDbType.DateTime).Value = chkIN;
cmd.Parameters.Add("#cDate", SqlDbType.DateTime).Value = chkDate;
cmd.Parameters.Add("#eNo", SqlDbType.Decimal).Value = empNo;
Also the syntax used in query could be the source of other problems, but I need to see your connection string.

Categories

Resources