问题
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