728x90
300x250

[C#.NET] - MySQL Blob 이미지 읽기, 저장하기

이번에 소개할 것은 C#에서 MySQL Blob를 사용하는 방법에 대해서 소개하려고 합니다.

1. 사용자 인터페이스 구현

그림1) 사용자 인터페이스 설계

c#에서 위의 그림처럼 작성합니다.

2. MySQL - Blob (이미지 저장)

        private void Btn_Save_Click(object sender, EventArgs e)
        {
            string SQL;
            UInt32 FileSize;
            byte[] rawData;
            FileStream fs;

            string ConString = "Server=hostName;Database=dbName;" +
                               "Uid=userID;Pwd=userPasswd;";

            MySqlConnection con = new MySqlConnection(ConString);
            MySqlCommand cmd = new MySqlCommand();
            BinaryReader br;
            try
            {
                fs = new FileStream(@txtPath.Text, FileMode.Open, FileAccess.Read);
                FileSize = (UInt32)fs.Length;

                rawData = new byte[FileSize];
                fs.Read(rawData, 0, (int)FileSize);
                fs.Close();

                con.Open();

                SQL = "INSERT INTO blob_tbl VALUES(NULL, @FileName, @FileSize, @File)";

                cmd.Connection = con;
                cmd.CommandText = SQL;
                cmd.Parameters.AddWithValue("@FileName", txtPath.Text);
                cmd.Parameters.AddWithValue("@FileSize", FileSize);
                cmd.Parameters.AddWithValue("@File", rawData);

                cmd.ExecuteNonQuery();

                MessageBox.Show("File Inserted into database successfully!",
                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                con.Close();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } // end of try to catch finally

        }
표1) 이미지 저장 소스코드



2. MySQL - Blob (이미지 읽기)

        private void Btn_dbLoad_Click(object sender, EventArgs e)
        {
            string SQL;
            string FileName;
            UInt32 FileSize;
            byte[] rawData;
            FileStream fs;

            string ConString = "Server=hostName;Database=dbName;" +
                               "Uid=userID;Pwd=userPasswd;";

            MySqlConnection con = new MySqlConnection(ConString);
            MySqlCommand cmd = new MySqlCommand();


            string query = "SELECT * from blob_tbl";

            try
            {
                con.Open();

                cmd.Connection = con;
                cmd.CommandText = query;

                MySqlDataReader myData = cmd.ExecuteReader();

                if (!myData.HasRows)
                    throw new Exception("There are no BLOBs to save");

                myData.Read();

                FileSize = myData.GetUInt32(myData.GetOrdinal("filesize"));
                rawData = new byte[FileSize];

                myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, (int)FileSize);

                FileName = @System.IO.Directory.GetCurrentDirectory() + "\\newfile.png";

                fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(rawData, 0, (int)FileSize);
                fs.Close();

                MessageBox.Show("File successfully written to disk!",
                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                pbBlobImg.Image = Image.FromFile(FileName);

                myData.Close();
                con.Close();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
      }
표2) 이미지 읽기 소스코드

4. 소스코드

Blob.zip
1.57MB



5. 데이터베이스 설계

그림2) 데이터베이스 설계

6. 시연

그림3) 시연하기

 

 

7. 참고자료(Reference)

 

MySQL :: MySQL Connector/NET Developer Guide :: 5.9.2 Writing a File to the Database

5.9.2 Writing a File to the Database To write a file to a database, we need to convert the file to a byte array, then use the byte array as a parameter to an INSERT query. The following code opens a file using a FileStream object, reads it into a byte arra

dev.mysql.com

https://dev.mysql.com/doc/connector-net/en/connector-net-programming-blob-writing.html

 

반응형

+ Recent posts