C#-在本地数据库中写入数据 [英] C# - Writing data in local database

查看:327
本文介绍了C#-在本地数据库中写入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序来保存密码.

Im working on a program to save Passwords.

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

I want to write them in a local database file (Name: 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

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

我想要Nr自动增量1(我已经在数据库中设置了该值). 我希望有人能帮助我. 我已经尝试了很多在Google上发现的东西,但似乎没有任何作用.

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)

Greetz, Rajco

推荐答案

您从未执行过该命令.

cmd.ExecuteNonQuery()

在conn.Close()之前

before the conn.Close()

并且您应该查看upp参数以避免sql-injection

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.

这篇关于C#-在本地数据库中写入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆