C#:将值插入数据库
本文关键字:插入 数据库 | 更新日期: 2023-09-27 18:27:04
我有一个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文件
首先,如果您复制了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)";