尝试上传图像时,“ConnectionString属性尚未初始化”

时间:2014-05-13 07:16:06

标签: c# asp.net

当我尝试使用此脚本从我的网页将图像插入我数据库中的表格时出现此错误:

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

public partial class editorlogin : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("");
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            //save image into database

            string str = FileUpload1.FileName;
            FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//uploads//"+ str);
            string path = "~/uploads/" + str.ToString();
            con.Open();
            SqlCommand cmd=new SqlCommand("Insert into upload values('" + TextBox1.Text + "','" + path + "')", con);
            cmd.ExecuteNonQuery();
            con.Close();
            Label1.Text = "Image Uploaded Successfully";


        }
        else
        {
            Label1.Text = "Please, Upload your image";
        }
    }
}
  

这是我得到的错误" ConnectionString属性尚未初始化。"

非常感谢任何帮助,谢谢。

4 个答案:

答案 0 :(得分:3)

错误不言自明,您尚未在此处初始化连接字符串:

SqlConnection con = new SqlConnection("");

connection string在哪里?

您需要以下内容:

SqlConnection con = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)");

除此之外,您在此处sql-injection开放:

"Insert into upload values('" + TextBox1.Text + "','" + path + "')"

不要使用字符串来构建您的SQL查询,而是使用parameterized queries

答案 1 :(得分:2)

在这一行:

SqlConnection con = new SqlConnection("");

您没有提供值来告诉应用程序要连接哪个SQL服务器。你需要用一些东西来填充它。您可以在以下位置找到适当的连接字符串列表:

http://www.connectionstrings.com/sql-server/

答案 2 :(得分:1)

您的SqlConnection ConnectionString属性现在具有值。你在构造函数中传递它“”。 您应该使用以下内容:

"data source=YOUR_SERVER_NAME\SERVER_INSTANCE;initial catalog=DB_NAME;user=USER_NAME;password=PASSWORD"

答案 3 :(得分:1)

错误是非常基本和描述性的,你不应该将你的connectionclass构造函数保持为'空字符串'你需要在其中提供连接字符串 见下面的片段

//Wrong
SqlConnection con = new SqlConnection("");

//Right
string szConnectStr = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;";
SqlConnection con = new SqlConnection(szConnectStr);
con.Open
{
   //code here
}
con.Close();

希望有所帮助