I have a C# DateTime class and wanted to know how I need to format it in a SQL Server CE query to insert it into the database, I was hoping to have both the date and time inserted in. Currently when I try variations thereof I get invalid format exceptions.
Current format I'm using is: dd/MM/yyyy, was hoping to do something like dd/MM/yyyy hh:mm:ss.
The way I'm trying to do the insert is like so:
( ( DateTime )_Value ).ToString( "dd/MM/yyyy hh:mm:ss" )
Obviously hh:mm:ss isn't working, if that isn't there dd/MM/yyyy executes successfully in the query.
I've tried a few formats including what I've found on google but none have worked so far...
If you're worried about getting the format right at all, something has already gone seriously wrong. There are two things you need to do to correctly work with datetime values in any database, not just sqlce:
Make sure you're using a datetime type for the column (not a text type like varchar)
Make sure you're using a datetime parameter in a parameterized query, and not string concatenation.
If you do that, there is no formatting involved on your part. At all. Example:
void SetDate(int recordID, DateTime timeStamp)
{
string SQL = "UPDATE [sometable] SET someDateTimeColumn= #NewTime WHERE ID= #ID";
using (var cn = new SqlCeConnection("connection string here"))
using (var cmd = new SqlCeCommand(SQL, cn))
{
cmd.Parameters.Add("#NewTime", SqlDbType.DateTime).Value = timeStamp;
cmd.Parameters.Add("#ID", SqlDbType.Integer).Value = recordID;
cn.Open();
cmd.ExecuteNonQuery();
}
}
Never ever ever ever EVER use string manipulation to substitute values into sql queries. It's a huge no-no.
Try the following format:
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
Man, you do not need to convert string to DateTime.
Use a instance of a new DateTime and pass the date as parameter. Like this:
using (var ctx = new DBPreparoEntities())
{
var _client = from p in ctx.Client
select new Client
{
data = new DateTime(2016,08,17),
dateconf = null,
scod_cli = p.Rua,
valorini = 7214.62m,
};
return client.ToList();
}
don't use:
... data = DateTime.Parse("2016/12/10") // or other type convertions.
private void button1_Click(object sender, EventArgs e)
{
var cnn1 ="";//connection string
SqlCeConnection cnn = new SqlCeConnection(cnn1);
datetime dt4 = DateTime.Today.Date.ToString("yyyyMMdd").trim();//format
var qry ="insert into tbl_test(User_Id, DateOfJoin)values (11,'" + dt4 + "')";
cmd = new SqlCeCommand(qry, cnn);
try
{
dr = cmd.ExecuteReader();
}
catch (Exception ex)
{
string sr = ex.Message;
throw;
}
}
Above code worked for me.
sorry this is in vb.net, but this is a method i use to convert from a CE date/time format:
Public Shared Function ConvertSqlDateTimeFormat(ByVal s As String) As String
Dim theDate As New Text.StringBuilder
Dim sTemp As String = ""
Dim iIndex As Integer
If s.Length > 8 Then
'first we do the time
iIndex = s.IndexOf(" ", System.StringComparison.OrdinalIgnoreCase)
If iIndex > 0 Then
sTemp = s.Substring(iIndex).Trim
iIndex = sTemp.IndexOf(".", System.StringComparison.OrdinalIgnoreCase)
If iIndex > 0 Then
sTemp = sTemp.Substring(0, iIndex)
End If
End If
'next the date
theDate.Append(s.Substring(4, 2))
theDate.Append("/")
theDate.Append(s.Substring(6, 2))
theDate.Append("/")
theDate.Append(s.Substring(0, 4))
theDate.Append(" ")
theDate.Append(sTemp)
End If
Return theDate.ToString
End Function
Related
I am trying to stop the default value date "01/01/1900"to be entered in the table when the value of the textbox is null.I don't need validation on the form null textbox is ok
Thanks
using (SqlConnection con = new SqlConnection(WebConfigurationManager
.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand sc = new SqlCommand(#"Insert into ClinicalFollowUp (MBID, Diagnosis,
DateLastSeen, DateofDeath ) values(#MBID, Upper(#Diagnosis),
Convert (date, #DateLastSeen , 103), Convert (date, #DODeath, 103);", con))
{
sc.Parameters.AddWithValue("#MBID", txtMBID1.Text);
sc.Parameters.AddWithValue("#Diagnosis", txtDiagnosis.Text);
// Date Textbox
sc.Parameters.AddWithValue("#DateLastSeen", txtDateLastSeen.Text);
// Date Textbox
sc.Parameters.AddWithValue("#DODeath", txtDateDeath.Text);
}
con.close();
}
I'd do it this way, personally.
static public object ToDbNullableDate(this string s)
{
DateTime d;
var ok = DateTime.TryParse(s, out d);
return ok ? d : DbNull.Value;
}
Then in your code:
sc.Parameters.AddWithValue("#DateLastSeen", txtDateLastSeen.Text.ToDbNullableDate());
You should send the parameters in your command using
The correct data type (NOT as string and do not convert them in Sql Server!)
Specify the data type of the parameter
Specify the length of parameter data types where appropriate. I guessed at your string lengths in the schema, update it accordingly.
Execute the conversion as early as possible in your call stack. Ideally you have a control that is a datetime picker, maybe this can do the conversion for you OR if its a web api then let the serializer deserialize the request to the approriate types.
const string sqlStatement = #"Insert into ClinicalFollowUp (MBID, Diagnosis, DateLastSeen, DateofDeath )
VALUES(#MBID, #Diagnosis , #DateLastSeen, #DODeath);"
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
using (SqlCommand sc = new SqlCommand( , con))
{
con.Open();
sc.Parameters.Add(new SqlParameter("#MBID", SqlDbType.VarChar, 100){Value = txtMBID1.Text});
sc.Parameters.Add(new SqlParameter("#Diagnosis", SqlDbType.VarChar, 2000){Value = txtDiagnosis.Text.ToUpper()});
// Date Textbox
sc.Parameters.Add(new SqlParameter("#DateLastSeen", SqlDbType.DateTime){Value = getSqlDate(txtDateLastSeen.Text)});
// Date Textbox
sc.Parameters.Add(new SqlParameter("#DODeath", SqlDbType.DateTime){Value = getSqlDate(txtDateDeath.Text)});
sc.ExecuteNonQuery();
}
// TO DO - validate culture information
public static object getSqlDate(string dateTime)
{
DateTime dt;
return !string.IsNullOrEmpty(dateTime) && DateTime.TryParse(dateTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)
? (object) dt
: (object) System.DBNull.Value;
}
try like this:
if (string.IsNullOrWhiteSpace(txtDateLastSeen.Text)
{
sc.Parameters.AddWithValue("#DateLastSeen", DbNull.Value);
}
else
{
sc.Parameters.AddWithValue("#DateLastSeen", txtDateLastSeen.Text);
}
EDIT: IsNullOrWhiteSpace, as suggested, is a bit simpler.
I am using SQL Server database and there's a column named Cell(VARCHAR) data type. While reading using reader.Read() I get the Conversion error. Can anyone kindly explain the reason for the error?
This is my code:
string myConnection = dbController.connectionString;
string query1 = "SELECT ID, Name from Manager Where Cell = " + managerNo.Text;
using (var conn = new SqlConnection(myConnection))
using (var cmd = new SqlCommand(query1, conn))
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
managerID = reader.GetString(0);
mgrID.Text = managerID;
managerNames.Text = reader.GetString(1);
}
conn.Close();
}
I am reading the value from a textbox (managerNo). I have tested the query on SQL Server Management Studio as well:
select Name, DOB
from Contact
where Cell = 1233453411
When I use Cell = 1233453411 without the value as string I get the conversion error, however using Cell = '1233453411' as a string the result is fetched.
Whats the reason for this and how to solve this issue.
Thanks.
This is a comparison between two different types, a string and an integer:
where Cell = 1233453411
SQL Server has to decide which type to use. It decides on the more restrictive type, which is the number. So, the string gets converted to a number.
Say, you have a cell phone in New York with a number like: 917-555-5555. Well, that becomes a number like 9,175,555,555 and this exceeds the value of the maximum integer. Hence, you would get a conversion overflow.
The moral: Always use similar types when making comparisons.
EDIT:
What should you do? Don't store telephone numbers as numbers; they should be stored as strings (for instance, leading zeroes can be important).
If could do a quick-and-dirty and put single quotes around the value of the parameter. But, what you should really do is change your SQL code to use a parameter with a string type. It is bad programming to just stuff values (particularly user input) into a query string.
Your code is working fine in SQL Server 2008 R2. (Below is tested code)
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\\SQL2008R2;Database=Practice;User ID=sa;Password=123;Trusted_Connection=True;Connection Timeout=0";
string query1 = "SELECT * from tblTest Where Cell = " + textBox1.Text;
using (var conn = new SqlConnection(str))
using (var cmd = new SqlCommand(query1, conn))
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string aa = reader.GetString(0);
}
conn.Close();
}
Otherwise using can change you query like in below format.
string query1 = "SELECT * from tblTest Where Cell = '" + textBox1.Text + "' ";
Thanks
I need some guidance for parsing dates. My database table contains values
ID (int) and date (datetime: yyyy-mm-dd HH:mm:ss.fff format) and status
example
1000 & 2014-02-18 20:32:20.657 & 1
2000 & 2014-02-18 20:32:20.658 & 1
3000 & NULL & -1
I have a C# program that looks at this table for status=1 and date not null and want to insert ID and Date in the same format in a text file.
The text file should have
1000 2014-02-18 20:32:20.657
2000 2014-02-18 20:32:20.658
Here's the code.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand cmdSel = new SqlCommand(sqlSelNew, connection);
SqlDataReader reader1 = cmdSel.ExecuteReader();
while (reader1.Read())
{
DataSet ds = GetData(sqlSelNew);
CultureInfo _provider = CultureInfo.InvariantCulture;
ID = Convert.ToInt32(reader1["ID"].ToString());
string dtformat = #"yyyy/MM/dd HH:mm:ss.fff";
var d = DateTime.ParseExact(dateresized,dtformat , _provider);
using (StreamWriter sw = new StreamWriter(txtfilepath, true))
{
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(ID + " " + d);
sw.Flush();
sw.Close();
}
I get "String was not recognized as a valid DateTime." error. How can I handle this?
Thanks
Rashmi
First, you shouldn't have to parse the date. You should simply be able to use reader.GetDateTime() to read that column and assign it. Second, why are you both filling up a DataSet and using a SqlDataReader to get the values directly? I'd expect one or the other but not both. Third, you ought to be wrapping your reader in a using statement as it implements IDisposable.
using (var reader1 = cmdSel.ExecuteReader())
{
while (reader1.Read())
{
var id = reader1.GetInt32(0);
var date = reader1.GetDateTime(1);
...
}
}
I built a query from a joint table, when I test it in the query builder it works fine but before I finish the wizard I get this message "no mapping exists from DB type AnsiString to known sql server".
I ignored the message then I tested the query function inside the windows form using C# language, when I run the program I got an exception with the similar message:No mapping exists from DbType AnsiString to a known SqlDbType..
here is my code:
SELECT SUM(Sales_Details.SalesP) AS Expr1
FROM Sales_Details INNER JOIN
Sales ON Sales_Details.Sl_ID = Sales.Sl_ID
WHERE (#date1 > Sales.Sl_Date) AND (#date2 < Sales.Sl_Date)
I tried to troubleshoot the issue, I deleted the last line of the code which is
WHERE (#date1 > Sales.Sl_Date) AND (#date2 < Sales.Sl_Date)
then the code works fine!!
I changed the data type of the parameters of the query to a DateTime but still showing the same exception error.
Here is my C# code:
private void button1_Click(object sender, EventArgs e)
{
DateTime d1 = Convert.ToDateTime(textBox1.Text);
DateTime d2 = Convert.ToDateTime(textBox2.Text);
int s = (int)queriesTableAdapter1.sellSumByDate(d1, d2);
MessageBox.Show("The total sells is "+s);
}
AGAIN I am sure that the exception is showing because of this line of code WHERE (#date1 > Sales.Sl_Date) AND (#date2 < Sales.Sl_Date)
what is the wrong with my code PLEASE?
or the problem is with my SQL or database version?
In C#, when you are using SqlCeCommand and ConnectionString, you have to add parameters
as shown below (You will have the required data in dataset Ds1.):
string con_str = "..."; // connection string
// initialise datetime variable with a proper datetime value
DateTime date1 = ... ;
DateTime date2 = ... ;
Database1DataSet Ds1 = new Database1DataSet(); // if you are reading from Database1
SqlCeConnection conn = new SqlCeConnection(con_str);
conn.Open();
SqlCeCommand Sqlce = new SqlCeCommand();
Sqlce.Connection = conn;
Sqlce.CommandText = "SELECT SUM(Sales_Details.SalesP) AS Expr1 " +
"FROM Sales_Details INNER JOIN " +
"Sales ON Sales_Details.Sl_ID = Sales.Sl_ID " +
"WHERE (#date1 > Sales.Sl_Date) AND (#date2 < Sales.Sl_Date)";
// add parameter values
Sqlce.Parameters.AddWithValue(#date1, date1);
Sqlce.Parameters.AddWithValue(#date2, date2);
SqlCeDataReader reader = Sqlce.ExecuteReader(); // this command executes your query
while (reader.Read())
{
Ds1.YourTable.Rows.Add(reader[0], reader[1], reader[2],..., reader[last column index]);
}
reader.Close();
conn.Close();
I want to read a datetime value from an SQLite database and assign it to a datepicker control.
Here is my code:
try
{
sqlitecon.Open();
string Query = "Select * from Customer_New where Cust_Id='" + val + "' ";
SQLiteCommand createCommand = new SQLiteCommand(Query, sqlitecon);
// createCommand.ExecuteNonQuery();
SQLiteDataReader dr = createCommand.ExecuteReader();
while(dr.Read()){
date_open.DisplayDate = Convert.ToDateTime(dr.GetString(0));
Date_Joining.DisplayDate = Convert.ToDateTime(dr.GetString(1));
txt_Title.Text = dr.GetString(3);
txt_cardnum.Text =dr.GetString(4)
}
sqlitecon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
but it is giving this error: "specified cast is not valid". How can it be done?.
If you already get a DateTime from the database you should not convert it to a string. Then just use:
date_open.DisplayDate = dr.GetDateTime(0);
instead of
date_open.DisplayDate = Convert.ToDateTime(dr.GetString(0));
If it's not a DateTime but a string(varchar) you should consider to change that.
Edit: Also note that you are using two different columns of the query to assign the datatime to your DateTimePicker, so right after above line you do mthis:
date_open.DisplayDate = Convert.ToDateTime(dr.GetString(1));
One of both must be incorrect. Which column is the datetime column?
Also, you should parametrize your queries to avoid sql-injection:
string Query = "Select * from Customer_New where Cust_Id=?1";
command.Parameters.Add(new SQLiteParameter { ParameterName = "1", Value = val });
(note that i have never used SqlLite, so the code is untested)
Select strftime([date],0) as [date] from Customer_New where Cust_Id=?1