Insert mysql datetime - c#

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

Related

Syntax Error Ocurring on the Data Reader

try
{
int i = 0;
using (SqlConnection sqlCon = new SqlConnection(Form1.connectionString))
{
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
// MessageBox.Show(commandString);
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
i = 1;
if (i == 0)
{
MessageBox.Show("Error in Logging In!", "Error");
}
MessageBox.Show("Successfully Logged In");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm making a LoginForm for a Project.I have created a table which shows the LoginDetails(Account,ID,LoginTime,LogoutTime).But when I run the Program,it doesn't runs successfully.I face an error which is in Pic-2.When I remove sql 'data reader',the program runs without displaying the error.
When you concatenate a null it basically adds nothing to the string, so this code:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
results of this string, and as you can see it has an extra comma, that causes the exception:
"INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('acc',textbxID,, SYSDATETIME());"
If you want to add NULL to the query it has to be a string, so do this instead:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID + ", NULL , SYSDATETIME()" + ");";
And you are using ExecuteReader instead of ExecuteNonQuery. You cannot use ExecuteReader for inserting rows to the DB.
Also, as someone mentioned in the other answer, you better do it with parametes to avoid SQL Injections.

Method returns empty string in ASP.Net

I'm having trouble with this method. It returns empty string, what is wrong with this ?
I have this method:
public static string GetData(string Table1, string Column1, string WhereColumn, string WhereValue)
{
Table1 = Methods.cleaninjection(Table1); // Some injection method that cleans the string
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString);
SqlCommand command = new SqlCommand("SELECT " + "#Column1" + " FROM " + Table1 + " WHERE " + "#WhereColumn" + " = " + "#WhereValue", connection);
command.Parameters.AddWithValue("Column1", Column1);
command.Parameters.AddWithValue("WhereColumn", WhereColumn);
command.Parameters.AddWithValue("WhereValue", WhereValue);
try
{
if ((connection.State == ConnectionState.Closed) || (connection.State == ConnectionState.Broken))
{
connection.Open();
}
string veri = Convert.ToString(command.ExecuteScalar());
return veri;
}
finally
{
connection.Close();
}
}
When I run this, the command string looks like this:
SELECT #Column1 FROM Table1 WHERE #WhereColumn = #WhereValue
It looks like correct but I couldn't find what is wrong.
Any ideas?
As commented, you cannot parameterize your column names and table names. Instead, do string concatenation:
"SELECT " + Column1 + " FROM " + Table1 + " WHERE " + WhereColumn + " = #WhereValue";
Here is how your code should be:
public static string GetData(string Table1, string Column1, string WhereColumn, string WhereValue)
{
Table1 = Methods.cleaninjection(Table1); // My injection method that cleans the string
string sql = "SELECT " + Column1 + " FROM " + Table1 + " WHERE " + #WhereColumn + " = #WhereValue";
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#WhereValue", SqlDbType.VarChar, 50).Value = WhereValue;
connection.Open();
string veri = Convert.ToString(command.ExecuteScalar());
return veri;
}
}
}
Notes:
Please do not use AddWithValue. Use Parameters.Add() instead. According to this article:
There is a problem with the AddWithValue() function: it has to infer
the database type for your query parameter. Here’s the thing:
sometimes it gets it wrong.
Wrap your object in Using to ensure proper cleanup of resources.
For additional security purposes, you can wrap your column name and table name in square brackets [].

Error updating table in SQL Server: Conversion failed when converting character string to smalldatetime data type

In C#, I want to write an update query with smalldatetime columns, I have seen several posts on Stackoverflow but I didn't find one to solve the error:
Conversion failed when converting character string to smalldatetime data type.
I have a table RESERVAS, with 3 columns ID_RESERVA (int), LLEGADA (smalldatetime), SALIDA (smalldatetime)
The code:
string strQuery = "UPDATE " + DB_TABLENAME + " SET " +
"LLEGADA = CONVERT(smalldatetime, '#LLEGADA', 126), " +
"SALIDA = CONVERT(smalldatetime, '#SALIDA', 126) " +
"WHERE ID_RESERVA = #ID_RESERVA";
SqlCommand cmd = new SqlCommand(strQuery, con); // con = SqlConnection
cmd.Parameters.Add("#ID_RESERVA", SqlDbType.Int);
cmd.Parameters.Add("#LLEGADA", SqlDbType.SmallDateTime);
cmd.Parameters.Add("#SALIDA", SqlDbType.SmallDateTime);
cmd.Parameters["#ID_RESERVA"].Value = Convert.ToInt32(stringWithIdReserva);
cmd.Parameters["#LLEGADA"].Value = stringWithLLegada.Replace(" ", "T"); //Real string value: "2015-03-30 00:00:00"
cmd.Parameters["#SALIDA"].Value = stringWithSalida.InnerText.Replace(" ", "T"); //Real string value: "2015-04-01 00:00:00"
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
That is because you have wrapped your parameters with single tick marks. The way you have it coded it is trying to parse the string literals instead of the values in your parameters.
string strQuery = "UPDATE " + DB_TABLENAME + " SET " +
"LLEGADA = CONVERT(smalldatetime, #LLEGADA, 126), " +
"SALIDA = CONVERT(smalldatetime, #SALIDA, 126) " +
"WHERE ID_RESERVA = #ID_RESERVA";
SqlCommand cmd = new SqlCommand(strQuery, con); // con = SqlConnection
cmd.Parameters.Add("#ID_RESERVA", SqlDbType.Int);
cmd.Parameters.Add("#LLEGADA", SqlDbType.SmallDateTime);
cmd.Parameters.Add("#SALIDA", SqlDbType.SmallDateTime);
cmd.Parameters["#ID_RESERVA"].Value = Convert.ToInt32(stringWithIdReserva);
cmd.Parameters["#LLEGADA"].Value = stringWithLLegada.Replace(" ", "T"); //Real string value: "2015-03-30 00:00:00"
cmd.Parameters["#SALIDA"].Value = stringWithSalida.InnerText.Replace(" ", "T"); //Real string value: "2015-04-01 00:00:00"
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}

my update c# code is not working,can i update two relational table at once?

i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here

how to insert a date from textbox to database

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

Categories