C#:将值插入数据库

时间:2014-10-18 21:20:46

标签: c# wpf database insert database-connection

我有WPF应用程序,我有按钮SaveData,它调用函数InsertValuesIntoGAStatistics,我想将数据插入数据库,但没有插入任何内容我不知道问题在哪里看起来很好,我没有得到任何错误消息只是什么都没做。

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

按钮用于保存数据

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

这里是获取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);
    }
}

这是InsertValuesIntoGAStatistics函数,它应该将数据插入数据库

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

这部分代码在App.config文件中

1 个答案:

答案 0 :(得分:1)

首先,如果你复制了app.config文件,那么你有一个错误......你错过了开始括号 - 除此之外配置对我来说很好。

第二:尝试在“插入...”之前放置符号@,所以它看起来像这样:

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