我有这是为了写出下列给我的SQL Server Express数据库中的“添加配方”按钮的基本方式:C#无法建立SQL Server连接
- 配方名称
- 配方成分
- 配方说明
- 配方图片
的形式位于所述问题的底部,当我点击“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服务正在运行您的。任何人都可以提供我的建议,我在这里做错了吗?
表单的图像
[SQL注入警报](http://msdn.microsoft.com/en-us/library/ms161953%28v= sql.105%29.aspx) - 你应该**不**连接你的SQL语句 - 使用**参数化查询**来代替以避免SQL注入 –
您不指定服务器地址和密码。你也应该使用准备好的语句和一个“使用”你的sql连接。 – HectorLector
对于SQL Server ** Express **,默认情况下,您的服务器实例称为“SQLEXPRESS”。因此,请在连接字符串中尝试以下操作:'Data Source =。\ SQLEXPRESS; ....' –