简体   繁体   English

无法插入到SQL Server数据库

[英]Unable to insert to SQL Server database

using (Connection = new SqlConnection(connectionstring))                
{
    SqlCommand voegtoe = new SqlCommand("INSERT INTO Speler(Naam, Rugnummer, Leeftijd) VALUES(@Naam, @Rugnummer, @Leeftijd)");

    voegtoe.CommandType = CommandType.Text;
    voegtoe.Connection = Connection;
    voegtoe.Parameters.AddWithValue("@Naam", textBox1.Text);
    voegtoe.Parameters.AddWithValue("@Rugnummer", textBox2.Text);
    voegtoe.Parameters.AddWithValue("@Leeftijd", textBox3.Text);

    Connection.Open();
    voegtoe.ExecuteNonQuery();            
}

If I open my Database there's nothing added to it. 如果打开数据库,则不会添加任何内容。 I think it should add the text what the user puts in the textboxes. 我认为它应该添加用户在文本框中输入的文本。

The connection string is: 连接字符串为:

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirector‌​y|\Speler.mdf;Integr‌​ated Security=True

There's nothing wrong with the code. 代码没有错。 I suspect that your connection string uses a User instance database, ie it has the AttachDBFilename and User Instance=true keywords: 我怀疑您的连接字符串使用了用户实例数据库,即它具有AttachDBFilenameUser Instance=true关键字:

Data Source=.\SQLEXPRESS; AttachDBFilename=|DataDirectory|\db.mdf; User Instance=true;...

That means that each user that tries to attach to the database file gets his own copy. 这意味着每个尝试附加到数据库文件的用户都将获得自己的副本。 When you try to check the data with SSMS you see a different copy of the database. 当您尝试使用SSMS检查数据时,您会看到数据库的另一个副本。

Apart from causing confusion, this feature is deprecated and will be removed in the future. 除了造成混乱之外,不建议使用此功能,以后将删除该功能。

Just create a proper database in your database server and connect to it by specifying its name: 只需在数据库服务器中创建一个适当的数据库并通过指定其名称来连接到它:

Data Source=.\SQLEXPRESS; Initial Catalog=MyDB;...

You can create the database either from the New Database menu in SSMS, or with a CREATE DATABASE MyDB command 您可以从SSMS的“ New Database菜单或使用CREATE DATABASE MyDB命令CREATE DATABASE MyDB

You can find more information in Bad habits : Using AttachDBFileName by Aaron Bertrand 您可以在“ 不良习惯”中找到更多信息 Aaron Bertrand 使用AttachDBFileName

What happens when your query hasn't been able to run? 当您的查询无法运行时会发生什么? If you would get an Exception you have to retry your insert. 如果出现异常,则必须重试插入。

The ExecuteNonQuery() method is able to return the amount of rows inserted. ExecuteNonQuery()方法能够返回插入的行数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM