试图将数据添加到数据库中,但没有添加到表中
本文关键字:添加 数据库 数据 | 更新日期: 2023-09-27 18:16:37
我试图添加一些数据到数据库中,但它没有在数据库表中添加,但它也没有显示任何异常。我不知道出了什么问题
try
{
SqlConnection con = new SqlConnection(@"data source=(LocalDB)'v11.0;attachdbfilename=|DataDirectory|'Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue','10')", con);
cmd.ExecuteNonQuery();
con.Close();
}
我的应用配置文件
[![<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="StoreContext" connectionString="data source=(LocalDB)'v11.0;attachdbfilename=|DataDirectory|'Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /></connectionStrings>
</configuration>][1]][1]
我的表 CREATE TABLE [dbo].[Store] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Item] VARCHAR (20) NOT NULL,
[Description] VARCHAR (100) NULL,
[Expences] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
您的请求中有一个错误,费用是一个整数:
SqlCommand cmd = new SqlCommand("insert into Store(Item,Description,Expences) values('pen','blue',10)", con);
尝试下面的代码,下面的代码是没有使用任何工具编写的,所以请尝试调整代码。
try
{
DbContext xyz = new DbContext();
Store oStore = new Store();
oStore.Item = "pen";
oStore.Description = "blue";
oStore.Expences = 10;
xyz.Stores.Add(oStore);
xyz.SaveChanges(); // never forgot to do SaveChanges
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}