【发布时间】:2025-12-08 22:45:01
【问题描述】:
我正在尝试使用基于服务的数据库将数据插入数据库我正在使用 Visual Studio 2010。我已经创建了表,但它在这里不起作用是我的代码: 如果您对如何插入数据库有代码建议,我将不胜感激。
public void AddAnimal(int animalID, string name, double age, string category, string gender, string extraAnimalInfo)
{
using (SqlConnection con = new SqlConnection(DBAccessLayer.Properties.Settings.Default.AnimalDBConnectionString))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand("INSERT INTO AnimalTable VALUES(@AnimalID, @Name, @Age, @Category, @Gender, @ExtraAnimalInfo)", con))
{
Console.WriteLine("Here 4");
command.Parameters.Add(new SqlParameter("AnimalID", animalID));
command.Parameters.Add(new SqlParameter("Name", name));
command.Parameters.Add(new SqlParameter("Age", age));
command.Parameters.Add(new SqlParameter("Category", category));
command.Parameters.Add(new SqlParameter("Gender", gender));
command.Parameters.Add(new SqlParameter("ExtraAnimalInfo", extraAnimalInfo));
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.WriteLine("Could not insert.");
}
}
更新1: 当我将数据插入数据库时,行会受到影响,但是当我从服务器资源管理器中打开数据库表时,什么都没有改变。
当我将数据插入数据库时,行会受到影响,但是当我从服务器资源管理器中打开数据库表时,我看不到任何变化。
【问题讨论】:
-
定义“不工作”。抛出异常?哪个例外?什么消息与该异常相关联?
-
按照 Eric J. 所说,将您的
Console.WriteLine("Could not insert.");更改为Console.WriteLine("Could not insert: " + ex);,您将获得一些有用的信息,您或我们可以使用它来诊断正在发生的事情。 -
当我将数据插入数据库时,行会受到影响,但是当我从服务器资源管理器中打开数据库表时,什么都没有改变。
-
检查您的连接字符串(方法开头的
Console.WriteLine(DBAccessLayer.Properties.Settings.Default.AnimalDBConnectionString);)与您在服务器资源管理器中查看的服务器/数据库的连接信息。听起来这里环境不匹配。
标签: c# database visual-studio-2010