-1

我正在尝试做以下事情:

  1. 将新图片添加到数据库中(添加到名为“PicProfile”的列中)。
  2. 将路径/位置复制到文本框(名为 image_path_txt)。另外,我可以用除图像之外的其他字段添加记录。

有人可以告诉我我做错了什么吗?

private void button1_Click(object sender, EventArgs e) 
{    
    byte[] imageBT = null;

    FileStream fstream = new FileStream(this.image_path_txt.Text, FileMode.Open, FileAccess.Read); 

     BinaryReader br = new BinaryReader(fstream);
     imageBT = br.ReadBytes((int)fstream.Length);
     string constring = "datasource=localhost;port=3306;username=root;password=amg135468lns";
     string Query = "insert into db.newuser (FName,LName,Age,Gender,Phone_No, Mobile_No,City, Street, Street_No,Email,idNewUser,PicProfile)"+ "values('" + this.Fname_txt.Text + "','" + this.Lname_txt.Text + "','"+this.Age_txt.Text+"','"+this.Gender+"','" + this.Phone_txt.Text + "','" + this.Mobile_txt.Text + "','" + this.City_txt.Text + "','" + this.Street_txt.Text + "','" + this.StreetNo_txt.Text + "','" + this.Email_txt + "','"+this.user_no_txt.Text+"',@PicP);";  

     MySqlConnection conDataBase = new MySqlConnection(constring);
     MySqlCommand cmdDataBase = new MySqlCommand(Query,conDataBase);
     MySqlDataReader myReader;

     try
     {
         conDataBase.Open();
         cmdDataBase.Parameters.Add(new MySqlParameter("@PicP", imageBT));

         myReader = cmdDataBase.ExecuteReader();
         MessageBox.Show("Saved");
         while (myReader.Read())
         {

         }

     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }

}
4

1 回答 1

2

空路径名是不合法的。

如果那是错误;这是不言自明的。您提供的是空路径。或者,换句话说,Textofthis.image_path_txt空的。


哇。因此,让我们从为什么不能将其添加到数据库中开始。您不能发出ExecuteReader反对INSERT声明。所以,而不是:

myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Saved");
while (myReader.Read())
{

}

这样做:

cmdDataBase.ExecuteNonQuery();

此外,而不是所有这些:

byte[] imageBT = null;

FileStream fstream = new FileStream(
    this.image_path_txt.Text,
    FileMode.Open,
    FileAccess.Read); 

BinaryReader br = new BinaryReader(fstream);
imageBT = br.ReadBytes((int)fstream.Length);

这样做:

byte[] imageBT = File.ReadAllBytes(this.image_path_txt.Text);

接下来,让我们继续进行资源管理。您需要在using此处利用该语句:

using (MySqlConnection conDataBase = new MySqlConnection(constring))
using (MySqlCommand cmdDataBase = new MySqlCommand(Query,conDataBase))
{
    // add parameters

    // execute the statement
}

接下来,让我们继续讨论 SQL 注入攻击。现在,您正在构建一个对 SQL 注入开放的查询,因为它没有完全参数化。它应该是这样的:

INSERT INTO tbl (field1, field2, field3) VALUES (@field1, @field2, @field3)

然后当您添加参数时,只需执行以下操作:

cmdDataBase.Parameters.AddWithValue("@field1", txtField1.Text);
cmdDataBase.Parameters.AddWithValue("@field2", txtField2.Text);
cmdDataBase.Parameters.AddWithValue("@field3", imageBT);
于 2013-10-07T13:42:35.433 回答