I'm trying to execute this query
"INSERT INTO Orders Values (" + OrderId.Text + ',' + IDCustTextBox.Text + ',' + CustName.Text + ",SELECT CONVERT(DATE, GETDATE()))"
To fix the query directly, first, you have mistmatched single quote. second, you can directly pass GETDATE()
int the value,
string _insert = "INSERT INTO Orders Values ('" + OrderId.Text + "','" + IDCustTextBox.Text + "','" + CustName.Text + "',GETDATE())"
Your sql statement is very weak. You should parameterized the value to avoid SQL Injection
.
Assuming you are using SQL Server
string connStr = "connection string here";
string insertStatement = @"INSERT INTO Orders
Values (@ordID, @custID, @custName, GETDATE())";
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = insertStatement;
comm.Parameters.AddWithValue("@ordID", OrderId.Text);
comm.Parameters.AddWithValue("@custID", IDCustTextBox.Text);
comm.Parameters.AddWithValue("@custName", CustName.Text);
try
{
conn.Open();
conn.ExecuteNonQuery();
}
catch(SqlException ex)
{
// do something with the exception
// ex.ToString()
// don't hide it
}
}
}
To improve:
Command
and Parameter
to avoid from SQL Injection
Command
and Parameter
to avoid from SQL Injection
-- :D
try-catch
block to properly handle exceptionusing
statement to properly dispose objectSince you are using the INSERT INTO ...VALUES
, you don't need a SELECT
. You will use:
"INSERT INTO Orders
Values ('" + OrderId.Text + "','" + IDCustTextBox.Text + "','" + CustName.Text + "',GETDATE())"
By the way, you do not need to convert GETDATE()
to a date because it is already a date.
Cant you Modify Your table with DEFAULT GETDATE()?? then You dont want to insert separately. eg: CREATE TABLE Orders ( OrderId int NOT NULL PRIMARY KEY, ProductName varchar(50) NOT NULL, OrderDate datetime NOT NULL DEFAULT GETDATE() )