Come recuperare i dati da un database SQL Server in C#?

Ho una tabella di database con 3 colonne firstname, Lastname e age. Nella mia applicazione C# Windows ho 3 textbox chiamate textbox1... Ho fatto la mia connettività al mio SQL Server usando questo codice:

SqlConnection con = new SqlConnection("Data Source = .;
                                       Initial Catalog = domain;
                                       Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);

Vorrei ottenere dei valori dal mio database; se do un valore nella textbox1 deve corrispondere ai valori nel database e recuperare altri dettagli nelle textbox corrispondenti.

Ho provato questo metodo ma non funziona:

cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";

Come posso fare per recuperare tutti gli altri valori nelle caselle di testo?

 public Person SomeMethod(string fName)
        {
            var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();

            Person matchingPerson = new Person();
            using (SqlConnection myConnection = new SqlConnection(con))
            {
                string oString = "Select * from Employees where FirstName=@fName";
                SqlCommand oCmd = new SqlCommand(oString, myConnection);
                oCmd.Parameters.AddWithValue("@Fname", fName);           
                myConnection.Open();
                using (SqlDataReader oReader = oCmd.ExecuteReader())
                {
                    while (oReader.Read())
                    {    
                        matchingPerson.firstName = oReader["FirstName"].ToString();
                        matchingPerson.lastName = oReader["LastName"].ToString();                       
                    }

                    myConnection.Close();
                }               
            }
            return matchingPerson;
        }

Poche cose da notare qui: Ho usato una query parametrizzata, che rende il tuo codice più sicuro. Il modo in cui stai facendo la dichiarazione di selezione con la parte "where x = "+ Textbox.Text +"" ti apre a SQL injection.

Ho cambiato questo in:

  "Select * from Employees where FirstName=@fName"
  oCmd.Parameters.AddWithValue("@fname", fName);  

Quindi, ciò che questo blocco di codice farà è:

Eseguire un'istruzione SQL contro il vostro database, per vedere se ci sono nomi corrispondenti a quello che avete fornito. Se è così, quella persona sarà memorizzata in un oggetto Person (vedi sotto nella mia risposta per la classe). Se non c'è corrispondenza, le proprietà dell'oggetto Person saranno null.

Ovviamente non so esattamente cosa stai cercando di fare, quindi ci sono alcune cose a cui prestare attenzione: Quando ci sono più di 1 persona con un nome corrispondente, solo l'ultima verrà salvata e restituita. Se vuoi essere in grado di memorizzare questi dati, puoi aggiungerli ad una List .

Person per renderla più pulita:

 public class Person
    {
            public string firstName { get; set; }
            public string lastName { get; set; }
    }

Ora per chiamare il metodo:

Person x = SomeMethod("John");

Potete quindi riempire le vostre caselle di testo con i valori provenienti dall'oggetto Person in questo modo:

txtLastName.Text = x.LastName;
Commentari (5)

creare una classe chiamata DbManager:

Class DbManager
{
 SqlConnection connection;
 SqlCommand command;

       public DbManager()
      {
        connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=.     \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
        command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
     } // constructor

 public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
     {
        bool returnvalue = false;
        try
        {
            command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
            command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
 command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname; 
            connection.Open();
            SqlDataReader reader= command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {

                    lastname = reader.GetString(1);
                    firstname = reader.GetString(2);

                    age = reader.GetString(3);

                }
            }
            returnvalue = true;
        }
        catch
        { }
        finally
        {
            connection.Close();
        }
        return returnvalue;

    }

poi fate doppio clic sul pulsante retrieve (es. btnretrieve) sul vostro modulo e inserite il seguente codice:

 private void btnretrieve_Click(object sender, EventArgs e)
    {
        try
        {
            string lastname = null;
            string firstname = null;
            string age = null;

            DbManager db = new DbManager();

            bool status = db.GetUsersData(ref surname, ref firstname, ref age);
                if (status)
                {
                txtlastname.Text = surname;
                txtfirstname.Text = firstname;
                txtAge.Text = age;       
               }
          }
       catch
          {

          }
   }
Commentari (1)

Per recuperare i dati dal database:

private SqlConnection Conn;
 private void CreateConnection()
 {
    string ConnStr =
    ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
 CreateConnection();
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}
Commentari (0)