-2

I'm trying to execute this query

"INSERT INTO Orders Values (" + OrderId.Text + ',' + IDCustTextBox.Text + ',' + CustName.Text + ",SELECT CONVERT(DATE, GETDATE()))"
4

3 回答 3

5

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:

  • use Command and Parameter to avoid from SQL Injection
  • use Command and Parameter to avoid from SQL Injection -- :D
  • use try-catch block to properly handle exception
  • use using statement to properly dispose object
于 2013-03-30T14:52:07.380 回答
1

Since 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.

于 2013-03-30T14:52:14.797 回答
0

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

于 2013-03-30T15:10:28.947 回答