【问题标题】:C# - Writing data in local databaseC# - 在本地数据库中写入数据
【发布时间】:2014-03-20 12:33:23
【问题描述】:

我正在开发一个保存密码的程序。

我想将它们写入本地数据库文件(名称:Database.sdf)。

这是我的 SQL 查询:

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();

但不知何故,它不起作用。 这是我的数据库设置: http://imgur.com/0JxX79y

我想要 Nr 自动增量 1,(我已在数据库中设置)。 我希望有人可以帮助我。 我已经尝试了很多我在 google 上找到的东西,但似乎没有任何效果。

问候, 拉杰科

【问题讨论】:

  • 1) 您使用的是哪个数据库? 2) 使用parameterized queries。这种字符串连接对 SQL 注入 攻击是开放的。 3) 你没有用ExecuteNonQuery 执行你的命令。 4) 不要将密码存储为纯文本。
  • 您的查询应该是 SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Passwords (Username, Password, Email, Website, Description, Rating, DateTime) VALUES ('" + UsernameBox.Text + "', " + PasswordBox.Text + "', '" + EmailBox.Text + "', '" + WebsiteBox.Text + "', '" + DescriptionBox.Text + "'," + RatingValue.Value + "," + DateTime。现在 + ")", conn);
  • 添加到Soner:1.使用实体框架,2.不要存储纯文本密码!
  • 我正在使用本地数据库(我在“添加新项目 --> 本地数据库”中添加了该数据库)。 2,当然让我们这样做,3我应该如何执行它?

标签: c# database local


【解决方案1】:

你从未执行过命令。

cmd.ExecuteNonQuery()

在 conn.Close() 之前

你应该查找upp参数以避免sql注入

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/catch。
  • 传递查询时出错。 [token line number = 1, token like offset = 113, token in error = ,]
  • 查看我编辑的答案,将您的数据设置为参数。您可能缺少或添加了一些字符。
  • 我猜数据库中的 Nr 是表的 ID?您不会设置它,因为它会自动设置。
  • 我需要为此添加什么参考?导致使用 System.Data.SqlClient;不是吗..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多