且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

本地数据库不保存数据。

更新时间:2022-10-19 17:55:51

将sdf文件标记为仅作为副本,如果不同或从解决方案中删除它并将其保留在1个位置,例如:应用程序的bin


添加值时尝试匹配参数名称。所以它说的是:

 command.Parameters.Add( new  SqlCeParameter( 标题,title)); 



应为:

 command.Parameters.Add( new  SqlCeParameter(  @ Title,title)); 


我不是积极的,但是我想我以前见过一些数据库配置有一个自动提交的标志或没有...你可能想确保在你的情况下打开自动提交...或者在添加记录后发送提交

Hello,

When I try to insert something into my Local Database (SQL Compact) it does add. But it doesn't save. I have tried serveral things. Here is my code:

Connection String

public static SqlCeConnection Connect()
{
    SqlCeConnection connection = new SqlCeConnection();
    connection.ConnectionString = @"Data Source=|DataDirectory|\Database\Database.sdf";
    connection.Open();

    return connection;
}



The "Add" Class.

public static void AddTodo(string title, string description, string content)
{
    SqlCeCommand command = new SqlCeCommand("insert into items (title, description, content) values (@Title, @Description, @Content)", Database.Connect());
    command.Parameters.Add(new SqlCeParameter("Title", title));
    command.Parameters.Add(new SqlCeParameter("Description", description));
    command.Parameters.Add(new SqlCeParameter("Content", content));
    command.ExecuteNonQuery();
    Database.Disconnect();
}



Last piece of code

private void addButton_Click(object sender, RoutedEventArgs e)
{
    TodoAdder.AddTodo(titleBox.Text, descriptionBox.Text, contentBox.Text);
}



When I rebuild database it deletes it. Or it never is in there.

Thanks in advance.

Updated question:
When I execute the insert query it does show up in the ListBox. But when I check my Database it is empty. Also, when I restart the program. It is empty again.

Mark the sdf file as copy only if different or remove it from your solution and keep it only in 1 location e.g.: bin of your application


Try matching your parameter names when you add the values. So where it says this:
command.Parameters.Add(new SqlCeParameter("Title", title));


should be:

command.Parameters.Add(new SqlCeParameter("@Title", title));


I'm not positive, but I think I've seen before that some database configs have a flag for auto-commit or no... you may want to make sure auto-commit is turned on in your case... or send a commit after you add the record.