从ASP.NET文本框将数据写入SQL数据库

时间:2016-05-06 19:01:19

标签: c# mysql asp.net sql-server database

写入SQL数据库时,我收到的是System.Web.UI.WebControls.TextBox'而不是实际数据本身。

upload.aspx.cs文件(包含查询):

 string query = "INSERT INTO reports (birdname, location, details, image, spotteddata, uploaddata, typeofbird) VALUES ('"+birdnametext+"', 'mygarden', 'some details about how long you waited', ' " + img + "', '10th March 2014','" + dateNow + "', '2')";

upload.aspx(包含文本框):

<header> Upload </header>
<p> Please fill out the form below to put your item up for sale</p>
<p>  
<span>Name of Bird:
<asp:TextBox ID="birdnametext" runat="server"></asp:TextBox> </span>
<br/>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Image ID="Image1" runat="server" />
<br />

3 个答案:

答案 0 :(得分:2)

他们可能是你做错了:

  1. 您正在尝试将TextBox本身传递给数据库,您需要传递它的Text。这意味着...'"+ birdnametext + "' ...应为...'"+ birdnametext.Text + "' ...
  2. 您正在通过文本查询打开injection的大门,而不是使用参数化查询。
  3. 您可以构建如下命令:

    string query = "INSERT INTO reports(birdname, location) VALUES(@birdname, @location);
    SqlCommand cmd = new SqlCommand("query,con);
    cmd.Parameters.Add("@birdname", SqlDbType.VarChar).Value = birdnametext.Text;
    cmd.Parameters.Add("@location", SqlDbType.VarChar).Value = "mygarden";
    // similarly you can add the rest of columns and parameters 
    cmd.ExecuteNonQuery();
    

答案 1 :(得分:1)

您需要使用TextBox的Text属性来访问其内容:

... + birdnametext.Text + ...

参数化,非连接

此外,在构建查询时,您不希望使用字符串连接,因为它可能使您容易受到SQL注入和语法不良等问题的影响。更好的方法是使用参数化,如下所示:

using(var connection = new SqlConnection("{your-connection-string}"))
{
     // Notice the use of parameters
     var query = "INSERT INTO reports (birdname, location, details, image, spotteddata, uploaddata, typeofbird) VALUES (@birdname, @location', @details, ' @uploadData, @someDate, @now, @x)";
     using(var command = new SqlCommand(query, connection))
     {
          connection.Open();
          // Read the bytes of your image here and store in a byte[]
          var imageData = File.ReadAllBytes(Image1.ImageUrl);
          // Add your parameters
          command.Parameters.AddWithValue("@birdName",birdnametext.Text);
          command.Parameters.AddWithValue("@location","mygarden");
          command.Parameters.AddWithValue("@details","some details about how long you waited");
          command.Parameters.AddWithValue("@uploadData",imageData);
          command.Parameters.AddWithValue("@someDate","10th March 2014");
          command.Parameters.AddWithValue("@now",DateTime.Now);        
          command.Parameters.AddWithValue("@x",2);  
          // Execute your query
          command.ExecuteNonQuery();
     }
}

答案 2 :(得分:0)

在sql语句中将birdnametext更改为birdnametext.text