Hello and thanks for reading.
I'm trying to insert the current date into my table, but I can't figure out how to write it correctly.
Here is my C# code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
conn.Open();
string Comment = UserWriteComment.Text;
string ID = DetailedID.Text;
string Name = DetailedName.Text;
string UniqueID = lblID.Text;
string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)" + "Values('" + ID + "', '" + Name + "', '" + Comment + "', '" + UniqueID + "', '" + Date + "')";
using (SqlCommand com = new SqlCommand(query, conn))
{
com.ExecuteNonQuery();
UserWriteComment.Text = "";
}
In the Query, There is a value called Date. This is here I like the Function to pass the current date into my Table.
I hope you can help me because I didnt managed to find the answer anywere.
Thanks:)
Use DateTime.Now or (in the database via sql) GetDate(). But more important, use sql-parameters to prevent sql-injection and conversion/localization issues:
string insertSql = #"INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)
Values(#ID, #Name, #Comment, #UniqueID, #Date)";
using (var conn = new SqlConnection("...."))
using (var com = new SqlCommand(insertSql, conn))
{
com.Parameters.AddWithValue("#ID", ID);
com.Parameters.AddWithValue("#Name", Name);
com.Parameters.AddWithValue("#Comment", Comment);
com.Parameters.AddWithValue("#UniqueID", UniqueID);
com.Parameters.AddWithValue("#Date", DateTime.Now);
conn.Open();
com.ExecuteNonQuery();
}
The using-statement ensures that unmanaged resources like the connection will be disposed/closed even in case of an error.
Use DateTime.Now instead of Date. i.e. update the INSERT line to the following.
string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)"
+ "Values('" + ID + "', '" + Name + "', '" + Comment + "', '"
+ UniqueID + "', '" + DateTime.Now + "')";
P.S: You really should be using Parameterize statements to avoid a Bobby Tables situation.
To fix this, implement it as shown by #Tim in his answer:
Instead of Date, try using the following
DateTime.Now
Another function that can help you is
GETDATE()
Date inserts for SQL Server is best used via :
GetDate()
or
Convert(Varchar, GetDate(), 101)
Note: converting the GetDate() value to varchar type 101 shortens the value to just the date w/o time stamp.
Related
Can someone please help me figure out why I am getting 'System.Web.UI.WebControls.TextBox' in MySQL database instead of actual values being entered in the text field. The code I am using is below ..
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
string queryStr;
string connString=System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnectionString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name, Last_Name, Email_Address, Phone_Number, Username, Password)" + "VALUES('" + firstnameTextBox + "','" + middlenameTextBox + "','" + lastnameTextBox + "','" + emailaddressTextBox + "','" + phonenoTextBox + "','" + usernameTextBox + "','" + passwordTextBox + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
I have tried all I could but still no luck. Any help would be really appreciated.
Thanks in Advance!
You are passing the TextBox itself to the database using the query. You need to pass the text instead. For this you can use .Text property of the TextBox control. Which gives you the Text/Content inside the Textbox Control. And one more advise for you. Use Parameterized queries instead for cuch queries to avoid Sql Injection.
For example:
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name)VALUES(#fName,#mName)";
SqlCommand cmd = new SqlCommand(queryStr);
cmd.Parameters.Add("#fName",SqlDbType.VarChar).Value=firstnameTextBox.Text ;
cmd.Parameters.Add("#mName",SqlDbType.VarChar).Value=middlenameTextBox.Text;
// Build your command like this
// Execute the command then
you should use .Text after the name of TEXTBOX.
For Example :-
string insert = "insert into table_Name (Name, Contact, Email) values ('" + txtname.Text + "', '" + txtcontact.Text + "', '" + txtemail.Text + "')";
when i inserting data into database i need to insert date also but i pass a insert query in this query i inserted data but it took date column by default SQL database date format but i want to display when the user enter data to insert data base that date i want to display my tried query is:
string s = "insert into BatchPermissons(BatchId,SubjectId,AuditoName,AudioID,CreatedBy,CreatedDate) values(" + batchno + ", " + subjectid + " , '" + AudiotoName + "', " + AudioId + ",'" + CBY + "'," + DateTime.Now.ToString() + ")";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
but the above query inserting default date in database.i need to insert when i insert data that particular date will be store can any one help me out.
If the date input will always be the current date then you can use the sql method getdate() to fill the value. if it is not, you have to give the date in proper format, that means in "yyyy-MM-dd HH:mm:ss" it is simple to change the format using .ToString() so the query will be :
string s = "insert into BatchPermissons(...,CreatedDate) values(...," + getdate() + ")"; // using standard method date
Or
string s = "insert into BatchPermissons(...,CreatedDate) values(...," + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ")"; // using formated date
Special note:
Can we stop opening way to sql injection using text only queries and start writing parameterised queries? So that we can avoid the unwanted FormatingException and also give protection from injection. In this case you can use parameterised queries like the following:
string QuerySql = "insert into BatchPermissons(BatchId,SubjectId,AuditoName,AudioID,CreatedBy,CreatedDate)" +
"values(#batchno,#subjectid,#AudiotoName,#AudioId ,#CBY,#dtime)";
SqlCommand cmd = new SqlCommand(s);
cmd.CommandType = CommandType.Text;
cmd.CommandText = QuerySql;
cmd.Parameters.Add("#batchno", SqlDbType.VarChar).Value = batchno;
cmd.Parameters.Add("#subjectid", SqlDbType.VarChar).Value = subjectid;
cmd.Parameters.Add("#AudiotoName", SqlDbType.VarChar).Value = AudiotoName;
cmd.Parameters.Add("#AudioId", SqlDbType.VarChar).Value = AudioId;
cmd.Parameters.Add("#CBY", SqlDbType.VarChar).Value = CBY;
cmd.Parameters.Add("#dtime", SqlDbType.DateTime).Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if you are using the getdate() method then you can avoid the last Parameter from adding value, it will be like the following:
"values(#batchno,#subjectid,#AudiotoName,#AudioId ,#CBY,getdate())"
You can replace the DateTime.Now.ToString() with "getdate()". This will take the date from SQL server. Or add format to the ToString
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
If your Database column type is datetime then try to insert datetime directly like this-
string s = "insert into BatchPermissons(BatchId,SubjectId,AuditoName,AudioID,CreatedBy,CreatedDate) values(" + batchno + ", " + subjectid + " , '" + AudiotoName + "', " + AudioId + ",'" + CBY + "'," + DateTime.Today + ")";
I've been building a small inventory system for my workplace and have stumbled on an error that I cannot seem to fix
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
I have no idea what to change here.
Any help would be appreciated.
Problem: You are missing the comma after location parameter in your query.
Solution: You need to separate the parameters using a comma.
Suggestion : Use parameterized queries to avoid SQL Injection Attacks.
Try this:
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber=#Inventorynumber,Inventory_Name=#Inventory_Name, Quantity =#Quantity ,Location =#Location,Category =#Category WHERE Inventorynumber =#Inventorynumber";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#Inventory_Name",name);
cmd.Parameters.AddWithValue("#Quantity",quant);
cmd.Parameters.AddWithValue("#Location",location);
cmd.Parameters.AddWithValue("#Category",category);
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(numquery));
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
Yes the error is in the missing comma, but this is the result of all that mess with string concatenation that ends always in subtle syntax errors.
Why don't you use a parameterized query? It is a lot simpler to write and you avoid parsing errors like this and (more important) you avoid Sql Injections
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
string query = "UPDATE Inventory SET Inventorynumber=#num, Inventory_Name=#name, " +
"Quantity =#qty,Location =#loc, Category =#cat " +
"WHERE Inventorynumber =#numquery";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, serverconnection);
cmd.Parameters.AddWithValue("#num", Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#qty", quant);
cmd.Parameters.AddWithValue("#loc", location);
cmd.Parameters.AddWithValue("#cat", category);
cmd.Parameters.AddWithValue("#numquery", Convert.ToInt16(numquery));
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
As a side note I have some doubts about some parameters type. Are you sure that quantity is really a string as implied by the presence of quotes around your original value?
Also the numquery and num variables are of type string, you try to convert then to short integer and then you put them inside quotes (meaning that in the database the fields are of type text). This makes no sense at all. If the database expects numbers then do not use quotes, if the database expects strings then do not try to convert. Another reason to use a parameterized query that force you to reflect on these issues.
You are missing a Comma between location and category. You have heard this million times befor i know, but its really much better using prepared statements so you do not have to take care of this kind of things and your code is much more readable.
You missed the comma
Location ='" + location + "', Category ='" + category + "'
// see the `,` between Location and Category
you have missed comma(,) in query:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Make it as:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "', Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Try removing the ' single quotes around the integers?
I'm experiencing difficulties filtering a set of data between two DateTime values.
For example: Retrieve all records From: 24/04/2013 3:54 PM; To: 24/04/2013 4:30 PM.
I'm programming in C# and using OLE DB to pull data from a Access Database.
The 'To' and 'From' DateTime values are retrieved from DateTimePicker controls on a GUI.
I'm trying to query data in 'receiveDateTime' field of my data source - it is stored in DateTime format in Access.
My code appears as follows:
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN "
+ fromDateTime.Value.ToString("g") + "AND " + toDateTime.Value.ToString("g")";
loadDataGrid(SQLQuery);
Any solutions or advice would be much appreciate.
Thanks,
Allan.
1- It seems you forgot the single quotes between the date values:
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN '"
+ fromDateTime.Value.ToString("g") + "' AND '" + toDateTime.Value.ToString("g") +"' ";
2- It would be better if you use parameterized parameters too:
SqlConnection con = new SqlConnection(MyconnectionString);
con.Open();
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN #dateFrom AND #dateTo";
SqlCommand cmd = new SqlCommand(SQLQuery );
cmd.Parameters.AddWithValue("#dateFrom", fromDateTime.Value.ToString("g"));
cmd.Parameters.AddWithValue("#dateTo", toDateTime.Value.ToString("g"));
SqlDataReader reader = cmd.ExecuteReader();
//...
You could have guessed the issue by trying to execute this query directly in your database
(I have used SQLConnection, SQLCommand... here, you will need to change that part based on the connection you are using.)
For anyone that encounters this problem in future when comparing DateTime value, passing the C# DateTime as an OLE Automation date to the database works!
In order to access this value you use the ToOADate() method.
For example:
SqlConnection con = new SqlConnection(MyconnectionString);
con.Open();
string SQLQuery = "SELECT EmailID, receiveDateTime "
+ "WHERE EmailTable.receiveDateTime "
+ "BETWEEN #dateFrom AND #dateTo";
SqlCommand cmd = new SqlCommand(SQLQuery );
cmd.Parameters.AddWithValue("#dateFrom", fromDateTime.Value.ToOADate());
cmd.Parameters.AddWithValue("#dateTo", toDateTime.Value.ToOADate());
It is quite strange, because although the DateTime values appear in general DateTime Format in the DataGrid, the database must read them as such:
General DateTime Format: 26/04/2013 9:47 AM
OLE Automation Date: 41390.4082198032
Thanks for pointing me in the right direction noobob!
I'm having the error at the line: ins.ExecuteNonQuery().ToString(); OledDbException was unhandled Syntax error in INSERT INTO statement.
How do I fix this?
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
string newTagID = textBox1.Text;
string newUser = textBox2.Text;
string newAge = textBox3.Text;
string newPhoneNumber = textBox4.Text;
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES ('" + newTagID + "', '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Connection.Open();
ins.ExecuteNonQuery().ToString();
ins.Connection.Close();
Your problem is probably one these three:
Outright syntax error not clearly visible with the hideous unparametrized SQL statement :p
newUser or some other field has a ' somewhere and is screwing up the syntax.
You are trying to insert a numeric value (Age?) as a string.
You should easily solve the first two creating a breakpoint after the insertString statement construction and checking out what the string really contains. The third one is even easier to check, just review the data types of the table's fields in your data base.
Notwithstanding, you should change the use of your command to use parameters and not build the query string with string concatenation (which is susceptible to sql injection attacks).
The issue is most likely because [Tag ID], User, Age, [Phone Number] are not all strings. In your SQL, any non-string column data should not be wrapped by quotes (').
To fix the immediate problem (assuming [Tag ID] is an integer):
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (" + newTagID + ", '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
However, you should structure your code to avoid sql injection, have cleaner code, and also not worry about the quotes:
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (#TagID, #User, #Age, #PhoneNumber)";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Parameters.Add(new OleDbParameter("#TagID",newTagID);
ins.Parameters.Add(new OleDbParameter("#User",newUser);
ins.Parameters.Add(new OleDbParameter("#Age",newAge);
ins.Parameters.Add(new OleDbParameter("#PhoneNumber",newPhoneNumber);
ins.Connection.Open();
ins.ExecuteNonQuery();
ins.Connection.Close();