【问题标题】:C#: Inserting values into databaseC#:将值插入数据库
【发布时间】:2014-10-18 21:20:45
【问题描述】:

我有 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 文件中

【问题讨论】:

  • 你有没有逐行调试你的代码?你确定你的ConnectionStrings 是对的吗?当您添加参数值时,您的 command 究竟是什么样的?
  • DataDirectory 和 Copy Always 设置的另一个受害者? Take a look here
  • Connection.ConnectionStringGADatabase 缺少 .

标签: c# wpf database insert database-connection


【解决方案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)";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2012-09-10
    • 1970-01-01
    • 2018-07-04
    • 2018-11-10
    相关资源
    最近更新 更多