select rows by datetime in sqlite - c#

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')";

Related

Repeater Search Query String

How can I make my select line in C# check if news_title is like my query string named Search?
This is what I have tried without success. It's supposed to then fill a Repeater with results that are like the query string.
// Get data from database/repository
static DataTable GetDataFromDb()
{
string searchquery = HttpContext.Current.Request.QueryString["Search"].ToString();
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
con.Open();
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE ([news_title] " +
"LIKE '%' + " + searchquery + " + '%') Order By news_postdate", con);
var dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
It should be '%" + searchquery + "%'. However this kind of string concatenation is open for SQL injection. Try parameterized queries instead, something like this :
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title] " +
"LIKE #Search Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search","%" + searchquery + "%");
Or:
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title]" +
" like '%' + #Search+ '%' Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search",searchquery);
Although specify the type directly and use the Value property is more better than AddWithValue. Have a look at this Can we stop using AddWithValue() already?

Migrate data from informix db to sqlserver db

I try to Migrate the data for list of employees from informix db to sqlserver2012 db ,so firstly i select
-The data from the tables in informix like this :
string cmdText = "select * from permission where emp_num in( " + emplyeeRange + " ) and perm_date>=? and perm_date <=?";
DataTable permissionDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
cmdText = "select * from holid where emp_num in( " + emplyeeRange + " ) and end_date>=? and start_date<=? ";
DataTable vacationDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
cmdText = "select * from empmission where emp_num in( " + emplyeeRange + " ) and date(to_date)>=? and date(from_date)<=? ";
DataTable missionDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
-Then i delete the data from sqlserver in the same range date like this :
cmdText = "delete from permission where emp_num in( " + emplyeeRange + " ) and perm_date>=#from_date and perm_date <=#to_date";
sql_command.CommandType = CommandType.Text;
sql_command.Parameters.AddWithValue("#from_date", from_date.ToShortDateString());
sql_command.Parameters.AddWithValue("#to_date", to_date.ToShortDateString());
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "delete from holid where emp_num in( " + emplyeeRange + " ) and end_date>=#from_date and start_date<=#to_date ";
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "delete from empmission where emp_num in( " + emplyeeRange + " ) and to_date>=#from_date and from_date<=#to_date";
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
}
}
-Then Insert the updated data in sqlserver like this :
cmdText = "insert into permission select * from #permissionDT ";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#permissionDT", permissionDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.permissionType";
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "insert into holid select * from #vacationDT";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#vacationDT", vacationDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.holidType";
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "insert into empmission select * from #missionDT";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#missionDT", missionDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.empmissionType";
result = sql_command.ExecuteNonQuery();
}
}
My Main problem is :
This process takes so long time and decrease the performance of sqlserver ,How to optimize this code and the queries concerning the db operations ?
Replace your SQLCommand ("insert into holid select * from #vacationDT") by SQLBulkCopy it will write you your server a lot faster.
e.g.:
using (var sbc = new SqlBulkCopy(myCOnnection)
{
sbc.DestinationTableName = "holid";
sbc.WriteToServer(vacationDT);
}
You may have to set ColumnMappings and/or set identity insert/on-off before and after this. More on SQLBulkCopy: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx
Also, check if your DB has all the right indexes especially on start_date and end_date

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);

how to get data between two dates from sql server 2008 in asp.net

I'm using referenced date-picker control to select date. I get the error
Conversion failed when converting date and/or time from character string
public DataSet comsn(string x, DatePickerControl.DatePicker a, DatePickerControl.DatePicker b)
{
ConnectionStringSettings connectionstringsql = ConfigurationManager.ConnectionStrings["plprojectConnectionString"];
SqlConnection connectionsql = new SqlConnection(connectionstringsql.ConnectionString);
if (connectionsql.State != System.Data.ConnectionState.Open)
{
connectionsql.Open();
}
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "comm"); //<------ At this line error occurred [ Conversion failed when converting date and/or time from character string ]
adp.Dispose();
return ds;
}
You can make this work by controlling the date format. When supplied to sql server as a string, I always format my data only string using 'YYYY-MM-DD', i.e., using the ToString('yyyy-MM-dd') on a date field.
However, you are better of turning your query into a parameter driven sql.
i.e., instead of "date >= '" a.Calendardate.ToString("yyyy-MM-dd")
Use "date >= #ADate"
and the supply the parameter value as
cmd.Parameters.Add("ADate", SqlDbType.DateTime).Value = a.Calendardate
I am assuming your datepicker has a "DateTime" property I am treating a.Calendardate as the DateTime property
You can avoid the exception and sql injection by using a parameterized query.
Replace:
SqlCommand cmd = new SqlCommand("select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= '" + x + "' AND date>= '" + a.CalendarDate + "' AND date <= '" + b.CalendarDate + "' ", connectionsql);
With:
string sql = "select a_id,commtyp,comm,primm,c_id,agent from comm where a_id= #x AND date>= #a AND date <= #b "
var cmd = new SqlCommand(sql);
cmd.Parameters.Add("#x", SqlDbType.NVarChar, x);
cmd.Parameters.Add("#a", SqlDbType.DateTime, a);
cmd.Parameters.Add("#b", SqlDbType.DateTime, b);
cmd.Connection = connectionsql;

converting excel data to datetime using 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.

Categories

Resources