C# - Writing data in local database

依然范特西╮ 提交于 2020-01-06 14:10:22

问题


Im working on a program to save Passwords.

I want to write them in a local database file (Name: Database.sdf).

This is my SQL query:

SqlCeConnection conn = new SqlCeConnection();
conn.ConnectionString = "Data Source = Database1.sdf";
conn.Open();
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Passwords (Nr, Username, Password, Email, Website, Description, Rating, DateTime) VALUES ('" + UsernameBox.Text + "', " + PasswordBox.Text + "', '" + EmailBox.Text + "', '" + WebsiteBox.Text + "', '" + DescriptionBox.Text + "'," + RatingValue.Value + "," + DateTime.Now + ")", conn);

conn.Close();

But somehow it doesnt work. This is my database setup: http://imgur.com/0JxX79y

I want the Nr auto increment 1, ( i have setted that in the database). I hope someone can help me out. I've tried alot of things i found on google, but nothing seems to work.

Greetz, Rajco


回答1:


you never executed the command.

cmd.ExecuteNonQuery()

before the conn.Close()

And you should look upp parameters to avoid sql-injection

http://www.dotnetperls.com/sqlparameter

        SqlCeCommand cmd = new SqlCeCommand(@"
            INSERT INTO Passwords 
                (Username, Password, Email, Website, Description, Rating, DateTime) 
            VALUES 
                (@UserName, @Password, @Email, @WebSite, @Description, @RatingValue, @DateNow)", conn);
        cmd.Parameters.AddWithValue("UserName", UsernameBox.Text);
        cmd.Parameters.AddWithValue("Password", PasswordBox.Text);
        cmd.Parameters.AddWithValue("Email", EmailBox.Text);
        cmd.Parameters.AddWithValue("WebSite", WebsiteBox.Text);
        cmd.Parameters.AddWithValue("Description", DescriptionBox.Text);
        cmd.Parameters.AddWithValue("RatingValue", RatingValue.Value);
        cmd.Parameters.AddwithValue("DateNow", DateTime.Now);

Try to use this instead. It adds your data as parameters for the query instead.



来源:https://stackoverflow.com/questions/22533170/c-sharp-writing-data-in-local-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!