将数据插入数据库Visual

将数据插入数据库Visual

本文介绍了将数据插入数据库Visual Studio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用基于服务的数据库将数据插入数据库中。我正在使用Visual Studio2010。我已经创建了表格,但是它在我的代码中不起作用:
如果您有

I am trying to insert data into a database using service-based Database I am using Visual Studio 2010. I have created the table but it doesn't work here is my code:I would appreciate if you have suggestion of code how to insert to a database.

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.");
            }
        }

UPDATE1:
当我将数据插入数据库时​​,行会受到影响,但是当我从服务器资源管理器中打开数据库表时,一切都没有改变。

UPDATE1:When I insert the data into the database the rows are affected but When I open the database table from the Server Explorer nothing have changed.

当我将数据插入数据库时​​,行会受到影响,但是当我从服务器资源管理器中打开数据库表时,我看不到任何更改。

When I insert the data into the database the rows are affected but When I open the database table from the Server Explorer I don't see any changes.

推荐答案

我遇到了类似的问题。对我来说,它是连接字符串。最初我有

I had a similar problem. For me, it was the connection string. Originally I had

数据源= .\SQLEXPRESS; AttachDbFilename = + | DataDirectory | pr.mdf; +集成安全性= True;用户实例= True;

"Data Source=.\SQLEXPRESS;AttachDbFilename=" + "|DataDirectory|pr.mdf;" + "Integrated Security=True;User Instance=True";

当我替换| DataDirectory |具有数据库的完整路径(在解决方案浏览器中右键单击数据库,单击属性,然后使用完整路径)。有效。它似乎有几个不同的数据库副本...即\bin\Debug\文件夹中有它的副本。

When I replaced |DataDirectory| with the full path to the DB (right click on the DB in the solution explore, click properties and then use the full path). It worked. It seams as though there are a couple of different DB copies...i.e. there is a copy of it in the \bin\Debug\ folder.

这篇关于将数据插入数据库Visual Studio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:46