2013-04-03 63 views
0

我想使用基于服务的数据库将数据插入数据库我使用Visual Studio 2010.我创建了表,但它不起作用,这里是我的代码: 我会如果您有代码如何插入到数据库的建议,请加以理解。插入数据到数据库Visual Studio

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: 当我将数据插入到该行受影响的数据库,但是当我从服务器资源管理器没有打开数据库表发生了变化。


当我将数据插入到该行受影响的数据库,但是当我从服务器资源管理器打开数据库表我没有看到任何改变。

+0

定义“不工作”。抛出异常?哪个例外?什么信息与该异常相关联? –

+0

按照Eric J.的说法,将Console.WriteLine(“Could not insert。”);改为Console.WriteLine(“Could not insert:”+ ex);'你会得到一些有用的信息你或我们可以用它来诊断正在发生的事情。 –

+0

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

回答

0

sql insert命令需要values关键字前面的列名。

INSERT INTO AnimalTable(AnimalID,姓名,年龄,种类,性别,ExtraAniamlInfo)VALUES(@AnimalID,@Name,@Age,@Category,@Gender,@ExtraAnimalInfo)

+1

如果您指定每列,并按照它们在表格中出现的相同顺序,则不需要它。至少对于Oracle和其他一些。 –

+0

对于SQL Server也是如此 –

1

我也有类似的问题。对我来说,这是连接字符串。原来我有

“Data Source =。\ SQLEXPRESS; AttachDbFilename =”+“| DataDirectory | pr.mdf;” +“集成安全性=真;用户实例=真”;

当我替换| DataDirectory |使用数据库的完整路径(在解决方案探索中右键单击数据库,单击属性,然后使用完整路径)。有效。它接近好像有一些不同的数据库副本......即。在\ bin \ Debug \文件夹中有它的一个副本。

+0

我来自谷歌搜索相同的解决方案。它解决了我的问题。谢谢 – YourFriend