我已經成功構建了執行select命令的方法。它工作正常。然後我更改我的代碼SqlDataAdapter DA = new SqlDataAdapter();
嘗試在SqlDataAdapter中傳遞SqlCommand作爲參數
我試圖在參數中通過SqlCommand
作爲CommandType.Text
,但我無法成功完成。我得到錯誤。如果我可以將它作爲參數傳遞,有什麼辦法嗎?請參閱我的代碼。
運行的代碼(aspx頁面代碼)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
連接成功,類代碼
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
如何傳遞CommandType.Text
爲SqlDataAdapter
參數?
錯誤代碼
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
我收到此錯誤:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
你甚至可以使用try catch來捕獲錯誤返回.. –