2013-10-20 133 views
0

我有這是爲了寫出下列給我的SQL Server Express數據庫中的「添加配方」按鈕的基本方式:C#無法建立SQL Server連接

  1. 配方名稱
  2. 配方成分
  3. 配方說明
  4. 配方圖片

的形式位於所述問題的底部,當我點擊「A DD配方」按鈕,它使得在updatedate()方法的調用,這個方法看起來像這樣:

private void updatedata() 
{ 
     // filestream object to read the image 
     // full length of image to a byte array 
     try 
     { 
       // try to see if the image has a valid path 
       if (imagename != "") 
       { 
        FileStream fs; 
        fs = new FileStream(@imagename, FileMode.Open, FileAccess.Read); 

        // a byte array to read the image 
        byte[] picbyte = new byte[fs.Length]; 
        fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length)); 
        fs.Close(); 

        //open the database using odp.net and insert the lines 
        string connstr = @"Data Source=.;Initial Catalog=RecipeOrganiser;Persist Security Info=True;User ID=sa"; 

        SqlConnection conn = new SqlConnection(connstr); 
        conn.Open(); 
        string query; 
        query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values (" + textBox1.Text + "," + " @pic" + "," + textBox2.Text + "," + textBox3.Text + ")"; 

        SqlParameter picparameter = new SqlParameter(); 
        picparameter.SqlDbType = SqlDbType.Image; 
        picparameter.ParameterName = "pic"; 
        picparameter.Value = picbyte; 
        SqlCommand cmd = new SqlCommand(query, conn); 
        cmd.Parameters.Add(picparameter); 
        cmd.ExecuteNonQuery(); 
        MessageBox.Show("Image successfully saved"); 
        cmd.Dispose(); 
        conn.Close(); 
        conn.Dispose(); 
        Connection(); 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

我的問題是當過我點擊‘與填充信息添加配方’按鈕,它凍結在30秒左右然後顯示以下錯誤,我已檢查SQL Server服務正在運行您的。任何人都可以提供我的建議,我在這裏做錯了嗎?

enter image description here

表單的圖像

enter image description here

+1

[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v= sql.105%29.aspx) - 你應該**不**連接你的SQL語句 - 使用**參數化查詢**來代替以避免SQL注入 –

+0

您不指定服務器地址和密碼。你也應該使用準備好的語句和一個「使用」你的sql連接。 – HectorLector

+0

對於SQL Server ** Express **,默認情況下,您的服務器實例稱爲「SQLEXPRESS」。因此,請在連接字符串中嘗試以下操作:'Data Source =。\ SQLEXPRESS; ....' –

回答

1
string connstr = @"Data Source=.;Initial Catalog=RecipeOrganiser;Persist Security Info=True;User ID=sa"; 

需求是

string connstr = @"Server=localhost\{SERVER_NAME};Database=RecipeOrganiser;Trusted_Connection=True;"; 

你可以從屬性值的SERVER_NAME 「名稱」用戶的SQL服務器屬性

+0

我使用windows身份驗證登錄,我還沒有設置sa密碼我怎麼知道這是默認的? – JsonStatham

+0

因此它需要是「Server = localhost; Database = RecipeOrganiser; Trusted_Connection = True;」 – Izikon

+0

仍然無法連接 – JsonStatham

0

使用下面的鏈接

SqlConnection con = new SqlConnection("Data Source=servername\\SQLEXPRESS;Initial Catalog=databasename;User ID=sa;Password=yoursqlserverpassword"); 

希望它會幫助你

0

連接字符串不好看我...嘗試使用的.Net SqlConnectionStringBuilder類創建一個有效的連接字符串...設置DataSource,InitialCatalog和IntegratedSecurity或UserId和密碼屬性