J'ai construit avec succès ma méthode pour exécuter une commande de sélection. Cela fonctionne bien. Puis je change mon code pour SqlDataAdapter DA = new SqlDataAdapter();
Essayer de passer SqlCommand dans SqlDataAdapter comme paramètres
J'ai essayé de passer SqlCommand
comme CommandType.Text
dans les paramètres mais je ne peux pas le faire avec succès. J'ai une erreur. Est-il possible si je peux le passer en tant que paramètres. S'il vous plaît voir mon code.
code Course à pied (ASPX code page)
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);
}
}
réussie du code de classe de connexion
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();
}
}
Comment puis-je passer CommandType.Text
en tant que paramètres pour SqlDataAdapter
?
Code d'erreur
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();
}
}
Je reçois cette erreur:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
Vous pouvez même utiliser essayer attraper pour attraper les erreurs de retour .. –