简体   繁体   中英

Save picture into specific row in database MySQL using C#

I have project from my lecture to make application that save biodata (Student ID, Name, Departement, etc.) into database. And also I want to save picture profile into database MySQL.

Here's the function to save all data (except picture):

public bool isSignUp (String nim, String nama, String jenisKelamin, String prodi, String angkatan, String pass, String verifPass )
    {
         if (nim==null || nama==null || jenisKelamin==null || prodi==null || angkatan==null
            || pass==null || verifPass==null)
        {
            return false;
        }
         else if(pass.Equals(verifPass)==false)
        {
            return false;
        }
         else
        {
            String query = "insert into dbmahasiswa VALUES (@NIM, @Nama, @JenisKelamin, @ProgramStudi, @Angkatan,  @Password)";
            try
            {
                connect.Open();
                MySqlCommand cmd = new MySqlCommand(query, connect);
                cmd.Parameters.AddWithValue("@NIM", nim);
                cmd.Parameters.AddWithValue("@Nama", nama);
                cmd.Parameters.AddWithValue("@JenisKelamin", jenisKelamin);
                cmd.Parameters.AddWithValue("@ProgramStudi", prodi);
                cmd.Parameters.AddWithValue("@Angkatan", angkatan);
                cmd.Parameters.AddWithValue("@Password", pass);
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Warning");
                return false;
            }
            finally
            {
                connect.Close();
            }
            return true;
        }
    }

How to add function to insert picture (that will be profile picture) in this method?

Something like:

        string filename = Path.GetFileName(imageToSave.FileName);
        string fileExtension = Path.GetExtension(filename);
        int fileSize = imageToSave.ContentLength;

        if (fileExtension.ToLower() == ".jpg" ) /*you could add a check for what type of image you want to be allowed to save*/
        {
            Stream stream = postedFile.InputStream;
            BinaryReader binaryReader = new BinaryReader(stream);
            Byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
         

    SqlParameter paramImageData = new SqlParameter()
    {
    ParameterName = "@ImageData",
    Value = bytes
    };
cmd.ExecuteNonQuery();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM