我尝试编写然后从 SQL 表中删除。我的 WRITE 代码没问题,但是我的 DELETE 代码不能按我的意愿工作。
//SQL_ConnectionString defined above
SqlConnection SQL_Connection = new SqlConnection(SQL_ConnectionString)
string INSERT = "INSERT INTO " + tbTable_DAQ.Text + " (Date, Time, Comment)";
string VALUES = "VALUES " + " (@Date, @Time, @Comment)";
string SQL_WriteString = INSERT + VALUES;
DateTime DateTimeNow = DateTime.Now;
try
{
//get time
DateTimeNow = DateTime.Now;
//create SQL command object
SqlCommand SQL_Write = new SqlCommand(SQL_WriteString, SQL_Connection);
//attach values
SQL_Write.Parameters.AddWithValue("@Date", DateTimeNow);
SQL_Write.Parameters.AddWithValue("@Time", DateTimeNow);
SQL_Write.Parameters.AddWithValue("@Comment", "Table Access Test. ");
SQL_Write.ExecuteNonQuery();
//dispose & nullify SQL_Write
SQL_Write.Dispose();
SQL_Write = null;
}
catch (Exception eWrite)
{
MessageBox.Show(eWrite.ToString(), "SQL WRITE ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
//now delete inserted row from SQL table
string DELETE = "DELETE FROM " + tbTable_DAQ.Text + " ";
string FROM = "WHERE " + "Date = " + DateTimeNow + "AND " + "Time = " + DateTimeNow
+ "AND " + "Comment='Table Access Test.'"; //not working
string SQL_DeleteString = DELETE + FROM;
try
{
//create SQL command object
SqlCommand SQL_Delete = new SqlCommand(SQL_DeleteString, SQL_Connection);
SQL_Delete.ExecuteNonQuery();
//dispose & nullify SQL_Delete
SQL_Delete.Dispose();
SQL_Delete = null;
}
catch (Exception eDelete)
{
MessageBox.Show(eDelete.ToString(), "SQL DELETE ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
它给了我一个错误。我相信错误是由于日期和时间列的值造成的。在 WRITE 代码上,我认为 SQL 表会在(日期类型)和(time7 类型)DateTimeNow
接收到它时转换为。但是,要删除该特定行,值必须匹配(未完成转换),我不知道如何正确获取值。Date
Time