2013-10-20 134 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和密码属性