please help me to insert a date from a text box in dd-mm-yyyy format to sql server.
my code is as follows:-
int prio = Convert.ToInt32(Priority.Text);
string stdate = planstart.Text;
string endate= planend.Text;
string actst = actualstart.Text;
string acten = actualend.Text;
SqlConnection myconnection = new SqlConnection(constring);
SqlCommand mycommand = new SqlCommand();
DataSet mydataset = new DataSet();
SqlDataAdapter mydataadapter = new SqlDataAdapter();
myconnection.Open();
mycommand.Connection = myconnection;
mycommand.CommandText = " insert into project_status.dbo.Project_Status_Report values('" + projectcode.Text + "','" + projectname.Text + "',(select P_Code from project_status.dbo.Project_Type where Project_Type = '" + projecttype.Text + "')," + prio + ",'" + stdate + "','" + endate + "','" + actst + "','" + acten + "','" + currentstatus.Text + "','" + remark.Text + "','no');";
mycommand.CommandType = CommandType.Text;
mycommand.ExecuteNonQuery();
and it is throwing an exception saying:-
Conversion failed when converting date and/or time from character string.
You need to convert data according to you sql server formate that way you can resolve issue ..
Try
String UrDate = "27/12/2011";
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime validDate= Convert.ToDateTime(toDate, dateInfo);
or
Format String For Dates
// String to DateTime
String MyString;
MyString = "1999-09-01 21:34 PM";
//MyString = "1999-09-01 21:34 p.m."; //Depends on your regional settings
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
null);
Make use of Paramerize query to avoid SQL INJECTION...make code less error pron
Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query
Just a word of caution - you need to sanitize that query to prevent SQL injection attacks. Consider using parameterised queries. Read up about it, it's not really the scope of this answer.
You should create strongly typed DateTime objects first and then format them the way you need to insert. Consider the following modification to your code:
string stdate = DateTime.Parse(planstart.Text).ToString();
string endate = DateTime.Parse(planend.Text).ToString();
string actst = DateTime.Parse(actualstart.Text).ToString();
string acten = DateTime.Parse(actualend.Text).ToString();
EDIT
I removed the string parameter from the ToString() so you can get a valid DateTime string that's usable by SQL Server.
con.Open();
string query = "insert_demo";
/* date fromat Stored*/
TextBox2.Text = DateTime.Now.ToLongDateString();
SqlCommand com = new SqlCommand(query, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", TextBox1.Text.ToString());
com.Parameters.AddWithValue("#Date", TextBox2.Text.ToString());
com.ExecuteNonQuery();
Related
I'm trying to get the date to store as a string in a table, but the date keeps converting to a negative 4 digit number which correlates with the date, and I can't for the life of me figure out where I've messed up. Note that I'm using a combo of C# and SQL Server
foreach(DataRow dr in dt.Rows)
{
int qty = 0;
string pname = "";
SqlCommand cmd3 = con.CreateCommand();
cmd3.CommandType = CommandType.Text;
cmd3.CommandText = "insert into order_item values('" + orderid.ToString() + "','" + dr["product"].ToString() + "'," +
"'" + dr["price"].ToString() + "','" + dr["qty"].ToString() + "','"+ dr["total"].ToString() + "')";
cmd3.ExecuteNonQuery();
qty = Convert.ToInt32(dr["qty"].ToString());
pname = dr["product"].ToString();
SqlCommand cmd6 = con.CreateCommand();
cmd6.CommandType = CommandType.Text;
cmd6.CommandText = "update stock set product_qty = product_qty - " + qty + " where product_name = '"+pname.ToString()+"'";
cmd6.ExecuteNonQuery();
// date keeps getting updated to negative 4 digit number which coordinates with the date. ex: 14-01-2020 is converting to -2007.
SqlCommand cmd7 = con.CreateCommand();
cmd7.CommandType = CommandType.Text;
**cmd7.CommandText = "update stock_over_time set product_qty = product_qty - " + qty + ", date_changed = " + date.ToString("dd-MM-yyyy") + "" +
" where product_name = '" + pname.ToString() + "'";**
cmd7.ExecuteNonQuery();
}
The immediate problem is that:
, date_changed = " + date.ToString("dd-MM-yyyy") + "
will become
, date_changed = 15-01-2020
which is: -2006, which is (because of how dates are stored) some time in July 1894.
A bad fix for this would be to add quotes, but this is: bad - it has a range of problems to do with internationalization (is 08-01 the first of August? the 8th of January?), SQL injection, etc.
The correct fix is to use parameters throughout. For example:
cmd7.CommandText = #"
update stock_over_time
set product_qty = product_qty - #qty,
date_changed = #date
where product_name = #pname";
This, however, requires you to add parameters with the values.
The simplest way to do this would be with Dapper:
string pname = ...
int qty = ...
DateTime date = ...
con.Execute(#"
update stock_over_time
set product_qty = product_qty - #qty,
date_changed = #date
where product_name = #pname",
new { pname, qty, date });
Note: all of your database access should be parameterized, either like the above, or using raw ADO.NET, or using tools like EF etc. Not just this one place; everywhere.
A date should not be stored as a string datatype, instead change date-changed to a datetime type (or even just a date, since the values stored have no "time" element).
Also, it is advisable to use a parameterized query to avoid SQL injection
string sql = #"update stock_over_time set product_qty = product_qty - #qty, date_changed = #date where product_name = #pname";
using (SqlConnection connection = new SqlConnection(connString)
{
connection.Open();
using (SqlCommand cmd= new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#qty", SqlDbType.SqlInt32).value = qty;
cmd.Parameters.Add("#date", SqlDbType.SqlDateTime).value = date;
cmd.Parameters.Add("#pname", SqlDbType.Varchar, 50).value = pname;
cmd.ExecuteNonQuery();
}
}
I want to bring a records of commission on specific date. Here is my code;
globalxx = 0;
string month1 = dateTimePicker2.Value.Month.ToString();
string day1 = dateTimePicker2.Value.Day.ToString();
string year1 = dateTimePicker2.Value.Year.ToString();
string s2 = "#" + month1 + "/" + day1 + "/" + year1 + "#";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(xi))
{
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission='" + s2 + "'", conn);
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#DateCommission", s2)
});
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
dataGridView2.DataSource = results;
But the problem is it gives error at
adapter.Fill(results);
saying: "OleDB Excpetion has been handeled Data type mismatch in criteria expression."
I Need help.
My MS Access Schema is:
DateCommission: Date Time
DriverName: TEXT
DriveVehicleNumber: TEXT
CommissionedPrice: NUMBER
I am not got at parameter.
Here is the front end of c#;
Front End
Handle your date as that, and then concatenate a formatted string expression in the SQL:
string textDate = dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd");
string s2 = "#" + textDate + "#";
and then:
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission = " + s2 + "", conn);
Or (preferred) use a parameter of data type DateTime which you pass Value of the datepicker directly.
I keep on having this error "Incorrect datetime value '2/1/16 7:22:00 AM'. I am sending a datetime value to a datetime data type column in mysql.
This is my code :
String AMTime =(AMHour.Text + ':' + AMMinute.Text).ToString();
am = Convert.ToDateTime(AMTime);
// string am = AMTimeConvert.ToString("HH:mm:ss");
String NNTime = (NNHour.Text + ':' + NNHour.Text).ToString();
nn = Convert.ToDateTime(NNTime);
// string nn = NNTimeConvert.ToString("HH:mm:ss");
String PMTime = (PMHour.Text + ':' + PMMinute.Text).ToString();
pm = Convert.ToDateTime(PMTime);
// string pm = PMTimeConvert.ToString("HH:mm:ss");
if (Generic != null || Brand != null || ContainerNum != "" || status != "")
{
result = database.AddMedicinePrescription(PrescribedDays,Dosage,numprescribed,NumofIntake,am,nn,pm);
}
This is the code that is to connect to my db
public bool AddMedicinePrescription(int PrescribedDays, int Dosage, int numprescribed, int NumofIntake, DateTime am, DateTime nn, DateTime pm)
{
sqlstring = "INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)" + "VALUE (" + PrescribedDays + ", " + numprescribed + ", " + Dosage + ", " + NumofIntake + ", '"+ am +"', '"+ nn +"', '"+ pm +"' ) ";
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(sqlstring, connect);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
connect.Close();
return true;
}
catch (Exception error)
{
MessageBox.Show("Warning 2: " + error.Message);
return false;
}
Because you try to add your DateTime values as a character with single quotes like '"+ am +"'
You need to delete all single quotes for your DateTime values.
But more important, stop the string concatenation when you build your commands. You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also you need ExecuteNonQuery instead of using a MySqlDataAdapter since INSERT statement does not return any data. It just inserts your value.
using(var connect = new MySqlConnection(conString))
using(var cmd = connect.CreateCommand())
{
cmd.CommandText = #"INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)
VALUE (#PrescribedDays, #numprescribed, #Dosage, #NumofIntake, #am, #nn, #pm)";
// Add your parameters with specify their types and size.
connect.Open();
cmd.ExecuteNonQuery();
}
Also you might need to read: Bad habits to kick : choosing the wrong data type
I am trying to figure out the way to sum values of certain columns. How do I get Date month value from Date column where all values are in date (yyyy/mm/dd) format?
What I should write in :
WHERE Data = '"?????"' ";
I want to pick up date where month equals 12.
Here is my code :
MySqlConnection cnn = new MySqlConnection(connectionString);
cnn.Open();
string query = "select sum(SUMA) from `nuolatines pajamos` WHERE ID = '" + perdavimo1.id_permetejas.ToString() + "' WHERE Data = '"+ now.Month +"' ";
MySqlCommand createCommand = new MySqlCommand(query, cnn);
var sum = createCommand.ExecuteScalar().ToString();
nl_pajamos.Text = sum.ToString();
DateTime.Parse(stringobject,cultureinfo);
for example
DateTime.Parse("20-01-2014",new CultureInfo("nl-BE
im trying to insert data into my oracle database but i am getting "invalid month" error as
it seems that i cant convert the datetimepicker value of my form into oracle date or timestamp(7) please help!
my code
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " dd MM yyyy ";
string m = "insert into member(memberid,name,street,roadno,houseno,phoneno,joindate,sex) values(member_deptno.nextval,'" + a + "','" + b+ "','" + c + "','" + d + "','" + h + "','" + dateTimePicker1.Value.Date+ "','"+de+"')";
user parameterized sql insert.
e.g. parameterized select query
SqlConnection objConnection = new SqlConnection(connectionString);
objConnection.Open();
SqlCommand objCommand = new SqlCommand(
"SELECT * FROM User WHERE Name = #Name AND Password = #Password",
objConnection);
objCommand.Parameters.Add("#Name", tbName.Text);
objCommand.Parameters.Add("#Password", tbPassword.Text);
SqlDataReader objReader = objCommand.ExecuteReader();
As others have mentioned parameters are the way to go but I don't think they'll solve your issue.
I assume the CustomFormat shown in your snippet is the format Oracle wants. The problem is that when you call dateTimePicker1.Value.Date it gives you a DateTime object and since you're combining it with a string it executes the .ToString() method which results in a different format. You should put your format string in the .ToString() to control the output. Example:
dateTimePicker1.Value.Date.ToString("dd MM yyyy");