I have a field date in DataTable
jeudi 12 mars 2015
vendredi 13 mars 2015
samedi 14 mars 2015
I need to store it in a table in sql server test which have a column datedes type date
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES('" + dt.Rows[i][j] + "')", con);
command.ExecuteNonQuery();
The code above always return error in conversion date.
how to resolve it ?
You need something like this:
Convert your rows[i][j] to a DateTime
use properly parametrized query in ADO.NET to insert your date
Code something like this:
// this might not work right now - you need to adapt this to that
// you can convert your strings like 'vendredi 13 mars 2015' to a
// valid "DateTime" object
DateTime dateTimeFromRow = Convert.ToDateTime(dt.Rows[i][j]);
// set up your DB connection string
string connectionString = "....";
// define your insert query with PARAMETERS
string insertQuery = "INSERT INTO [test]([Datedes]) VALUES(#DateDes);";
// use "using" blocks to properly dispose of connection and command
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(insertQuery, conn)
{
// define and set value for parameter
command.Parameters.Add("#DateDes", SqlDbType.Date);
command.Parameters["#DateDes"].Value = dateTimeFromRow;
// open connection, execute INSERT, close connection
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
In your example, you try to insert a string to your date type table column which is wrong obviously.
Depending on what you are doing;
Change your date typed column to nvarchar and insert that string
Parse your string to DateTime and insert that value with parameterized query.
For first option, just change your column type to nvarchar.
For second option, you need parse your string with fr-FR culture (if it is not your CurrentCulture) and pass this value directly.
var s = "samedi 14 mars 2015";
var dt = DateTime.Parse(s, CultureInfo.GetCultureInfo("fr-FR"));
using (var con = new SqlConnection(conString))
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO [test] ([Datedes]) VALUES(#date)";
cmd.Parameters.Add("#date", SqlDbType.Date).Value = dt;
con.Open();
cmd.ExecuteNonQuery();
}
What you are doing wrong is you try to parse data type string to datetime. And from your information the datetime format is not legal to parse. I suggest you to create another string type's field to store 'jeudi' 'vendredi' or 'samedi'.
Use to cut string :
var targetString = "jeudi 12 mars 2015";
var resultString = "";
int index;
foreach (var item in targetString)
{
if (int.TryParse(item.ToString(), out index) && !string.IsNullOrWhiteSpace(item.ToString()))
{
resultString = targetString.Substring(index);
}
}
//resultString == "12 mars 2015"
Afterthat use :
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES("#date")", con);
command.Parameters.AddWithValue(#date, resultString);
command.ExecuteNonQuery();
Do not append string like you do because it's not secure.
Related
I am new to C#, and learning. I have a SQL Server database where I have table record that has a column dob of data type date. I am trying to insert into dob from my textbox which has a value of 19-08-17 with the following code
datebox.Text = "19-08-17";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", datebox.Text);
com.ExecuteNonQuery();
But I get this error
Conversion failed when converting date and/or time from character string.
How can I solve this?
When you pass a variable to a DateTime column as a parameter, you need to convert the text to a DateTime variable before passing it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].Connect ionString);
// Convert the textbox text to a DateTime variable
DateTime myDate = DateTime.ParseExact(datebox.Text, "dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", myDate);
com.ExecuteNonQuery();
I have a datetime column named submitted_date. One of it's value in database is 5/12/2017 11:09:50 AM. Now I want to extract only date and month part of it. How to display it in a format like "May-12".
My code is here,
using (SqlConnection con = obj.getcon())
{
con.Open();
string query = "SELECT submitted_date FROM sample";
using (SqlCommand command = new SqlCommand(query, con))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string x_val = reader[0].ToString(); // 5/12/2017 11:09:50 AM
}
}
}
con.Close();
}
To get the alphabetic month name you can use MMM. Here is the code:
var result = DateTime.Parse(reader[0].ToString())
.ToString("MMMM-dd", CultureInfo.InvariantCulture);
//if reader[0].ToString(): 5/12/2017 11:09:50 AM then
//result: May-12
Use DATEPART directly on SQL and you're done.
You can do this with the following, but you will need to know which culture so as to get the month name in the correct language. I have used the US culture in this example:
string s = reader.GetDateTime(0).ToString("MMMM-dd", CultureInfo.CreateSpecificCulture("en-US"));
This also assumes that your submitted_date column is NOT NULL.
You can write query like:
Convert(varchar(20),submitted_date,107) submitted_date which will return date on Dec 12, 2016.
Try this:
from:
string x_val = reader[0].ToString(); // 5/12/2017 11:09:50 AM
To:
string x_val =DateTime.Parse(reader[0].ToString()).ToString("MMM-dd");
I've got cells in an excel file that contain data like:
"2006","2005","2015"
It is read into a datagridview temporarily, which is later inserted into an access database like so:
using (OleDbConnection conn = new OleDbConnection(Con))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText =
"Insert INTO ACTB (ID,Business,Account,Description,Span_Year,Period,Amount_PHP,Project_Number,Status_Regime,Department,Description_Dept,Accounts,Class) " +
"VALUES(#ID,#Business,#Account,#Description,#Span_Year,#Period,#Amount_PHP,#Project_Number,#Status_Regime,#Department,#Description_Dept,#Accounts,#Class)";
for (int s = 0; s < DGVExcel.Rows.Count; s++)
{
cmd.Parameters.Clear();
int theDoubleDate = Convert.ToInt32(DGVExcel.Rows[s].Cells[4].Value);
DateTime theDate = DateTime.FromOADate(theDoubleDate);
cmd.Parameters.AddWithValue("#ID", DGVExcel.Rows[s].Cells[0].Value);
cmd.Parameters.AddWithValue("#Business_Unit", DGVExcel.Rows[s].Cells[1].Value);
cmd.Parameters.AddWithValue("#Account", DGVExcel.Rows[s].Cells[2].Value);
cmd.Parameters.AddWithValue("#Description", DGVExcel.Rows[s].Cells[3].Value);
cmd.Parameters.AddWithValue("#Span_Year", theDate);
cmd.Parameters.AddWithValue("#Period", DGVExcel.Rows[s].Cells[5].Value);
cmd.Parameters.AddWithValue("#Amount_PHP", DGVExcel.Rows[s].Cells[6].Value == null ? 0 : Convert.ToDouble(DGVExcel.Rows[s].Cells[6].Value));
cmd.Parameters.AddWithValue("#Project_Number", DGVExcel.Rows[s].Cells[7].Value);
cmd.Parameters.AddWithValue("#Status_Regime", DGVExcel.Rows[s].Cells[8].Value);
cmd.Parameters.AddWithValue("#Department", DGVExcel.Rows[s].Cells[9].Value);
cmd.Parameters.AddWithValue("#Description_Dept", DGVExcel.Rows[s].Cells[10].Value);
cmd.Parameters.AddWithValue("#IS_Accounts", DGVExcel.Rows[s].Cells[11].Value);
cmd.Parameters.AddWithValue("#ITR_Class", DGVExcel.Rows[s].Cells[12].Value);
cmd.ExecuteNonQuery();
}
}
}
However, these write the values wrong, like 8/7/1905 all ending in 1905.
Another requirement is that the end value be day and month agnostic, meaning the value would come up as say: 2016 => 1/1/2016, just before the data is inserted into the database. Some have suggested that I merely use int values, however, datetime is required for me because I intend to use the between keyword to easily look up data between certain periods.
Edit: I just realized that some of my data might not have a year listed. Normally, I could be able to insert nulls just fine, however, if I'm doing some convert before that, I'm sure it will throw an exception like Cannot convert DB.Null into other types.
You can check if there is a value in the cell and then create a new DateTime
if (string.IsNullOrEmpty(DGVExcel.Rows[s].Cells[3].Value))
{
cmd.Parameters.AddWithValue("#Span_Year", DateTime.Now.Date);
}
else
{
cmd.Parameters.AddWithValue("#Span_Year", new DateTime(Convert.ToInt32(DGVExcel.Rows[s].Cells[3].Value), 1, 1);
}
I would also recommend specifying the datatype in the parameter, this will provide more type-safety and prevent conversion errors with datetime.
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = 45;
cmd.Parameters.Add("#Span_Year", SqlDbType.DateTime).Value = date;
I Have a table with 3 columns, when an alarm goes off, I want the time of that alarm to be stored in the 2nd column of the table(AlarmActivated). Then if that alarm is turned off, it stores that time in the same row of the table but in column 3. This is my code:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString());
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.ExecuteReader();
Con.Close();
This is executed when a value goes to 0.
ExecuteReader returns some data. Since you wanna insert, you need to use ExecuteNonQuery instead.
And do not store your DateTime values as a string. Change your column type to datetime2 and pass your DateTime.Now value directly to your parameterized query. Please read Bad habits to kick : choosing the wrong data type
Also using DateTime.Now can be ambigious. Read Matt's article The case against DateTime.Now
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
Since you insert only one column, other two columns will be null or their default value.
string ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30"
using(var Con = new SqlConnection(ConStr))
using(var Command = Con.CreateCommand())
{
Command.CommandText = "INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarm)";
Command.Parameters.Add("#alarm", SqlDbType.DateTime2).Value = DateTime.Now;
Con.Open();
Command.ExecuteNonQuery();
}
The problem is in
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString())
It has to be
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (" + DateTime.Now.ToString() + ")";
wrong function is used, use this function: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx ExecuteNonQuery
First, your string for your insert is badly formed. You need to put the parentheses inside quotes:
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES('" + DateTime.Now.ToString() +"')";
Secondly, you need to use parameterized queries instead, because building your SQL like this is a bad habit to get into and can lead to SQL injection breaches:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarmTime)";
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.Parameters.AddWithValue("#alarmTime", DateTime.Now);
Command.ExecuteNonQuery();
Con.Close();
Finally, only the column AlarmActivated will be set with a value. The other two columns will be populated by their default value. If you want the other two columns to have a value other than their default, you need to specify them and provide a value.
You can create 2 stored procedures in SQL, one will insert row and return ##SCOPE_IDENTITY (you can store it in list<>), which you will use as a param for updating procedure.
Try to avoid using SQL statemensts in code, to prevent code injection.
Using Visual Studio 2010 and C#
Table1:
column datatype
------------------------
Currenttime time
How to insert a time value into table1?
Code
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
insert into table1 values(time)
Getting error
Cannot convert from string to System.Timespan
while inserting into table1.
Need Code help
You should always (no exceptions!) use parametrized queries instead of constructing your own SQL statement as a string! Just google "SQL injection" - it's a really horrible thing.... stop doing that RIGHT NOW
To use a parametrized query, you should get in the habit of using a pattern like this:
// Define your SQL query - WITH parameters!
// And always specify the list of columns for your INSERT!
string query = "INSERT INTO dbo.Table1(CurrentTime) VALUES(#TimeValue)";
// use the "using" blocks to properly protect your disposable connection and command
using (SqlConnection con = new SqlConnection("server=.;database=test;integrated security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
// set the parameter value
cmd.Parameters.Add("#TimeValue", SqlDbType.Time).Value = TimeSpan.Parse(time);
// open connection, execute your INSERT, close connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You need DateTime.Parse and not Timespan.parse , Timespan represents length of time
You need to parse to DateTime and not datetimepicker's itself, parse its value
DateTime.Parse(datetimepicker1.value)