Seda
Seda

Reputation: 103

C#: Inserting values into database

I´ve WPF application where i have button SaveData which calls function InsertValuesIntoGAStatistics and i want to insert data into database but nothing is inserted i don´t know where is problem everything looks fine and i didn´t get any error message just nothing is done.

private void SaveData_Click(object sender, RoutedEventArgs e)
{
    database.InsertValuesIntoGAStatistics("haha", 4, 4, 4, 4, 11, "hlalha", "blabla", "blabsdla");
}

button for saving data

public static string ConnectionStringGADatabase
{
    get
    {
        return ConfigurationManager.ConnectionStrings["GADatabase"].ConnectionString;
    }
}

here is property to get connectionString

public void InsertValuesIntoGAStatistics(string GAType, int Generations, int PopulationSize, float MaxFitness, float AverageFitness, int DmaxValue, string Selection, string CrossOver, string FilePath)
{
    try
    {
        using (SqlConnection connection = new SqlConnection(Connection.ConnectionStringGADatabase))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "INSERT INTO GAStatistics (GAType, Generations, PopulationSize, MaxFitness, AverageFitness, DmaxValue, Selection, CrossOver, FilePath) VALUES (@GAType, @Generations, @PopulationSize, @MaxFitness, @AverageFitness, @DmaxValue, @Selection, @CrossOver, @FilePath)";
            command.Parameters.AddWithValue("@GAType", GAType);
            command.Parameters.AddWithValue("@Generations", Generations);
            command.Parameters.AddWithValue("@PopulationSize", PopulationSize);
            command.Parameters.AddWithValue("@MaxFitness", MaxFitness);
            .............
            connection.Open();
            command.ExecuteNonQuery();
        }
    }
    catch (SqlException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

this is function InsertValuesIntoGAStatistics which should insert data into database

<connectionStrings>
<add name="GADatabase" connectionString="Data Source=LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database\GADatabase.mdf;Integrated Security=True" 
     providerName="System.Data.SqlClient" />
</connectionStrings>

and this part of code is in App.config file

Upvotes: 0

Views: 7253

Answers (1)

Eru
Eru

Reputation: 397

First of all if you have copied the app.config file, then you have an error in it... you are missing the opening bracket - apart from that the config looks fine to me.

Second: Try to put symbol @ before "insert into..." so it will look like this:

command.CommandText = @"INSERT INTO GAStatistics (GAType, Generations, PopulationSize, MaxFitness, AverageFitness, DmaxValue, Selection, CrossOver, FilePath) VALUES (@GAType, @Generations, @PopulationSize, @MaxFitness, @AverageFitness, @DmaxValue, @Selection, @CrossOver, @FilePath)";

Upvotes: 1

Related Questions