2013-11-15 46 views
1

嘿傢伙我在視覺工作室2012內使用連接字符串數據庫設置。 我想發送數據到數據庫沒有錯誤的代碼,但它沒有運行,任何幫助會很棒,因爲我現在已經呆了幾個小時,需要睡覺。 謝謝。數據輸入asp.net C#SQL

默認頁面代碼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Data; 

namespace WebApplication1 
{ 
    public partial class _Default : Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     protected void Button1_Click(object sender, EventArgs e) 
     { 
      SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0; Initial Catalog = Database1; Integrated Security = true"); 
      SqlDataAdapter da = new SqlDataAdapter(); 
      da.InsertCommand = new SqlCommand("INSERT INTO Adopter (FIRSTNAME,LASTNAME) VALUES (@FIRSTNAME,@LASTNAME)", cs); 
      da.InsertCommand.Parameters.Add("@FIRSTNAME", SqlDbType.VarChar).Value = firstname.Text; 
      da.InsertCommand.Parameters.Add("@LASTNAME", SqlDbType.VarChar).Value = lastname.Text; 

      cs.Open(); 
      da.InsertCommand.ExecuteNonQuery(); 
      cs.Close(); 
     } 

     protected void firstname_TextChanged(object sender, EventArgs e) 
     { 

     } 

     protected void lastname_TextChanged(object sender, EventArgs e) 
     { 

     } 


     } 
    } 

SQL代碼

CREATE TABLE [dbo].[Adopter] (
    [FIRSTNAME] VARCHAR (50) NOT NULL, 
    [LASTNAME] VARCHAR (50) NOT NULL, 
); 

我知道這將是一些簡單的...我只是不能看到它。

+0

它是否寫入您的表格?你甚至能夠連接到數據庫? 「它沒有運行」,對我們來說不足以幫助你。 – Brian

+0

Web應用程序加載允許我鍵入文本框,當我點擊按鈕它說cs.open有問題。所以它不會將數據輸入到數據庫表中。 – Beep

+1

您需要在連接字符串中指定您的'DataSource'(數據庫實例)以及'Initial Catalog'(這是數據庫名稱(您已經有了))。 – Brian

回答

1

因此,正如我們在評論中所討論的那樣,您的問題看起來像是連接字符串。您有:

SqlConnection cs = new SqlConnection("Data Source = (LocalDB)\v11.0; 
Initial Catalog = Database1; Integrated Security = true"); 

你需要的是:

SqlConnection cs = new SqlConnection("Data Source = .\SqlInstanceName; 
Initial Catalog = Database1; Integrated Security = true"); 

的數據源是本地計算機,託管數據庫或SQL實例的一番風味和「初始目錄」上的實例是實際的數據庫名稱。

PS - 我高度建議你看看using關鍵字,這樣,當他們摔倒外的範圍,他們會爲您管理用它包住您的命令和連接對象。它看起來有點像這樣當您使用它們:

using (SqlConnection cs = new SqlConnection()) 
{ 
    // Some code can go here. 

    using (SqlCommand cmd = new SqlCommand()) 
    { 
     // More code can go here. 
    } 
} 

我有關於它的this後更全面的答案。快樂的編碼!

+0

謝謝Brian – Beep