2

I want to save images in SQL database when selected by users. So far i have typed this code. This doesn't give me any error but doesn't add to the database. I think something is wrong with the SQL Statement.

can someone help me?

This is my code:

public void addImages(string tag1,string tag2,string tag3,string status,string fileName)
{
    try
    {
        byte[] image = null;
        FileStream fsstream = new FileStream(fileName,FileMode.Open,FileAccess.Read);
        BinaryReader br = new BinaryReader(fsstream);
        image = br.ReadBytes((int)fsstream.Length);

        SqlCommand command = new SqlCommand("INSERT INTO [ImagesAndTags] (Images,Tags,Tag2,Tag3,Status) values (@IMG,'" + tag1 + "','" + tag2 + "','" + tag3 + "','" + status + "')", con);
        con.Open();
        command.Parameters.Add(new SqlParameter("@IMG",image));
        SqlDataReader reader = command.ExecuteReader();
        MessageBox.Show("Added Successfully!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        while (reader.Read()) { }
    }
    catch(Exception ex) { }
}

2 Answers 2

3

ExecuteReader returns data. In your case, you are not. You just try insert a row in your database. That's why you need to use ExecuteNonQuery instead.

And parameterize your other insert values as you did for image variable. Also use using statement to dispose your database connections and commands.

int insertedRowCount = command.ExecuteNonQuery();

if(insertedRowCount > 0)
   MessageBox.Show("Added Successfully!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
Sign up to request clarification or add additional context in comments.

Comments

0

Remove all the backslash, single inverted-commas and double inverted commas from the DATA you are storing in the database.

Replace it with some constant string and while retrieving it back again convert it to original.

1 Comment

Um, what? If you're thinking he has to encode escaped data, you're wrong. For one thing, using a parameterized query would deal with that for him. For another, he's passing in an array of bytes (not a string), and thus isn't dealing with characters at that point (what the type on the db is, we don't know).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.