2015-03-13 83 views
0

嗯,我用C#工作一点点,现在我开始用C#处理数据库,我在几个地方搜索了一下,我无法确定它在哪里错误的,无处不在说我需要打开连接,但它已经打开。连接属性的错误尚未初始化

 SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf"); 
     con.Open(); 
     try 
     { 
      string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)"; 
      SqlCommand cmd = new SqlCommand(query); 
      cmd.ExecuteNonQuery(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
+0

我不确定你是否在搜索。但你应该搜索一个torutial或示例代码,你会发现很多,像这样http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program – Gouda 2015-03-13 17:43:49

回答

2

使用using,负责关闭和处置你,以防万一你忘记明确地做到这一点。把它放在try里面,你在try之外有连接open命令,所以它不会捕获任何连接错误。你可能也想看看参数化你的命令。

using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf")) 
{ 
     conn.Open(); 
     using (SqlCommand cmd = new SqlCommand("INSERT INTO [Table] (name, time) VALUES (@name,@time)", conn)) 
     { 
      cmd.Parameters.AddWithValue("@name", "test"); 
      cmd.Parameters.AddWithValue("@time", 1); 
      cmd.CommandType = CommandType.Text; 
      cmd.ExecuteNonQuery(); 
     } 
} 
+0

好吧,我觉得复杂(以我对C#的理解),并且帮助我更好地理解如何在.NET语言中工作,谢谢! – GtOkAi 2015-03-13 17:52:58

+0

@GOOkAi欢迎您! – Fred 2015-03-13 18:01:03

0

您需要将命令分配给连接。例如:

private static void ReadOrderData(string connectionString) 
    { 
     string queryString = 
      "SELECT OrderID, CustomerID FROM dbo.Orders;"; 
     using (SqlConnection connection = new SqlConnection(
        connectionString)) 
     { 

//---- 

      SqlCommand command = new SqlCommand(
       queryString, connection); 


//---- 
      connection.Open(); 
      SqlDataReader reader = command.ExecuteReader(); 
      try 
      { 
       while (reader.Read()) 
       { 
        Console.WriteLine(String.Format("{0}, {1}", 
         reader[0], reader[1])); 
       } 
      } 
      finally 
      { 
       // Always call Close when done reading. 
       reader.Close(); 
      } 
     } 
    } 
1
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf"); 
     try 
     { 
      string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)"; 
      SqlCommand cmd = new SqlCommand(query,con); 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      con.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
+0

它的工作,你能告诉我我做错了什么吗? – GtOkAi 2015-03-13 17:51:36

+0

@GOOkAi你犯了两个错误 1)你打开连接前需要 2)你犯的主要错误是没有将连接字符串传递给命令对象 SqlCommand cmd = new SqlCommand(query,con); – 2015-03-13 18:08:01

相关问题