converting excel data to datetime using c# - c#

I am new to C# and I have a C# program and an excel file exported from another program. How can I convert it to DateTime? Here is the code, where dtFrom and dtTo are DateTimePicker variables:
System.Data.DataTable dtExcel = new System.Data.DataTable();
dtExcel.TableName = "MyExcelData";
string SourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + this.textBox1.Text + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select Customer, SUM(Wt) AS Weight from [Sheet0$] WHERE (CONVERT(datetime, [Date]) >= " + this.dtFrom.Value.Month + ") GROUP BY Customer order by Customer";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);

I think it's probably not your only problem, but to answer your question, if you replace
string query = "Select Customer, SUM(Wt) AS Weight from [Sheet0$] WHERE (CONVERT(datetime, [Date]) >= " + this.dtFrom.Value.Month + ") GROUP BY Customer order by Customer";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
with
string query = "Select Customer, SUM(Wt) AS Weight from [Sheet0$] WHERE (CONVERT(datetime, [Date]) >= #Date) GROUP BY Customer order by Customer";
OleDbCommand command = new OleDbCommand(query);
command.Parameters.Add("#Date", OleDbType.DBTimeStamp).Value = this.dtFrom.Value;
OleDbDataAdapter data = new OleDbDataAdapter(command, con);
you'll probably be on the right track. Not 100% sure exactly which OleDbType you need, but you can see the available options easily enough.

Related

syntax error (missing operator) in query expression

I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.

select rows by datetime in sqlite

I am trying to select rows which are inbetween a startdate and an enddate in c# with sqlite.
my dates are formatted like this:
2015-05-16T17:22:04.920+02:00
which should be a valid format for sqlite (ref: http://www.sqlite.org/lang_datefunc.html)
i am trying to select the row like this:
string CmdString = "SELECT * FROM " + tablename + "WHERE DATETIME(timekey) >= DATETIME('2015-05-16T17:22:04.920+02:00') AND DATETIME(timekey) <= DATETIME('2015-05-16T17:24:04.920+02:00')";
SQLiteCommand cmd = new SQLiteCommand(CmdString, con);
SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
DataTable MatchDt = new DataTable();
sda.Fill(MatchDt);
The Error i get is:
SQLiteException: SQL logic error or missing database
What am I doing wrong?
You are missing a space char before the where:
string CmdString = "SELECT * FROM " + tablename + " WHERE DATETIME(timekey) >= DATETIME('2015-05-16T17:22:04.920+02:00') AND DATETIME(timekey) <= DATETIME('2015-05-16T17:24:04.920+02:00')";
And I would reccomend using the BETWEEN operator:
string CmdString = "SELECT * FROM " + tablename + " WHERE DATETIME(timekey) BETWEEN DATETIME('2015-05-16T17:22:04.920+02:00') AND DATETIME('2015-05-16T17:24:04.920+02:00')";

How do I get number of rows between two Dates/Times in SQL table?

How can get the number of rows between two dates and between two times in SQL database from my windows form application in c#?
As shown in the screenshot (SQL database), and using the following query I am trying to get the number of rows between two certain dates and times:
For example: The dates/times starts from today at 13:00:00 until now.
int NumberOfRows;
SqlConnection con = new SqlConnection("Data Source= pcn1;Initial Catalog=mydb;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Orders WHERE DateTime BETWEEN '" + DateTime.Today.AddHours(13).ToString("yyyy-MM-dd HH-mm-ss") + "' AND '" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
NumberOfRows= dt.Rows.Count;
The problem is: when I execute this query under button click it shows error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value". When I change the query format from yyyy-MM-dd HH-mm-ss to yyyy-MM-dd it works but it returns number of row = 0 (it should return 3) .
Anything I am doing wrong? Please help how to get the number of rows between certain dates/times as shown in the query.
Instead of formatting the DateTime values and concatenating them into the query string just use parameters.
SqlCommand command = con.CreateCommand();
command.CommandText = "SELECT * FROM Orders WHERE DateTime BETWEEN #FromDate AND #ToDate";
command.Parameters.Add("#FromDate", SqlDbType.DateTime).Value = DateTime.Today.AddHours(13);
command.Parameters.Add("#ToDate", SqlDbType.DateTime).Value = DateTime.Now;
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Orders WHERE DateTime BETWEEN '" + DateTime.Today.AddHours(13).ToString("yyyyMMdd HH:mm:ss") + "' AND '" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + "' ", con);
make changes in code as above and try.
sda = new SqlDataAdapter("SELECT * FROM Orders WHERE DateTime BETWEEN #from AND #to",con);
sda.SelectCommand.Parameters.AddWithValue("#from",fromDate);
sda.SelectCommand.Parameters.AddWithValue("#to",toDate);
fromDat and toDate are two DateTime objects;
This worked for me
string myScalarQuery = "select count(*) from TableName where WHERE DateTime BETWEEN #from AND #to";
SqlCommand myCommand = new SqlCommand(myScalarQuery, myConnection);
mycommand.Parameters.AddWithValue("#from",fromDate);
mycommand.Parameters.AddWithValue("#to",toDate);
myCommand.Connection.Open();
int count = (int) myCommand.ExecuteScalar();
myConnection.Close();

exporting dataset to sqlite3 database using c# application errors sqlexception unhandled

I am very new to sqlite and c# and trying exporting a csv file to sqlite database using dataset.
but I get this error.
SQL logic error or missing database
no such column: P17JAW
code:
string strFileName = "I:/exploretest.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data Source= C:/Users/WebMobility.db; Version=3;");
m_dbConnection.Open();
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var Id = dr["Id"].ToString();
var VRM = dr["VehicleRegistration"].ToString();
var Points = Convert.ToInt32(dr["TicketScore"].ToString());
string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "'," + VRM + "," + Points + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}
CSV FILE CONTAINS
Id,VehicleRegistration,TicketScore
21,P17JAW,1
22,K1WOM,1
23,m4npr,4
25,G7EPS,4
Your problem is with the single quotes missing for VRM your query should be like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
( '" + Id + "','" + VRM + "'," + Points + ")";
//^^ ^^
From the values it appears that ID is of integer type, you can remove single quotes around ID.
You should parameterized your query that will save your from these errors. I am not sure if parameters are supported by SQLiteCommand if they are you can do something like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
(#Id,#VRM,#Points)";
and then
command.Parameters.AddWithValue("#id", Id);
command.Parameters.AddWithValue("#VRM", VRM);
command.Parameters.AddWithValue("#Points", Points);

Search record in ACCESS DATABASE using c#

i am trying to find the records based on the user input in msaccess database.
below is the code
string strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Employees.mdb";
string strSql = "SELECT * FROM tbl_employees where description like '" + txtsearch.Text.ToString() + "*'";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataReader dr = cmd.ExecuteReader();
int columnCount = dr.FieldCount;
When i ran the same query in my SQLView of msaccess i am getting records but when i ran it in VS i am not getting any records.
I think your matching should be changed:
String strSql = "SELECT * FROM tbl_employees WHERE description LIKE '" + txtsearch.Text.ToString() + "%'";
//Replaced * with %

Categories

Resources