简体   繁体   中英

When I try to load image from mysql database i get error “Parameter is not valid” and when i try to load an image from db

The program is made in C# and database is MySQL. I have 2 errors, first one when program loads (parameter is not valid) and second one (You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(Slika) values (_binary '?PNG).

So i tried the @blob thing (before i was only saving it as pictureBox which people said its false) and i get this error.

Also good to mention that i always get saved the same file which is BLOB - 55B. This is the code:

private void button3_Click(object sender, EventArgs e)
        {
            con.OpenConnection2();
            string query2 = "update tabla set (Slika) values (@Blob)";
            cmd.Connection = Connectioncl.connection2;
            cmd.CommandText = query2;
            cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
            cmd.ExecuteNonQuery();
            MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
            pictureBox2.Image = pictureBox3.Image;
            this.Refresh();
        }

I get parameter is invalid in this code where image has to load from database as soon as program is started:

private void Form2_Load(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = Form1.id; //just to check if its the correct ID
                con.OpenConnection();
                label1.Text = Form1.ime;
                label2.Text = Form1.prezime;
                timer1.Start();
                string query = "select * from tabla where ID='" + ID + "'";
                cmd.Connection = Connectioncl.connection;
                cmd.CommandText = query;
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    pictureBox2.Image = displayImage((byte[])dr["Slika"]);

                }
                dr.Close();
                con.CloseConnection();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

And here is the whole code of the Form2 (Form1 works perfectly fine):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;

namespace Maturski_Rad_1
{
    public partial class Form2 : Form
    {
        Connectioncl con = new Connectioncl();
        MySqlCommand cmd = new MySqlCommand();
        string ID = Form1.id;

        public Form2()
        {
            InitializeComponent();
        }

        public byte[] save(PictureBox pb)
        {
            MemoryStream mstr = new MemoryStream();
            pictureBox3.Image.Save(mstr, pb.Image.RawFormat);
            return mstr.GetBuffer();
        }

        public Image displayImage(byte[] slika)
        {

            MemoryStream mstr = new MemoryStream(slika);
            return Image.FromStream(mstr);
        }  

        private void Form2_Load(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = Form1.id; //just to check if its the correct ID
                con.OpenConnection();
                label1.Text = Form1.ime;
                label2.Text = Form1.prezime;
                timer1.Start();
                string query = "select * from tabla where ID='" + ID + "'";
                cmd.Connection = Connectioncl.connection;
                cmd.CommandText = query;
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    pictureBox2.Image = displayImage((byte[])dr["Slika"]);

                }
                dr.Close();
                con.CloseConnection();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }


        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void panel1_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("Vas ID je: " + Form1.id, panel1);
            toolTip1.UseFading = true;
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label4.Text = DateTime.Now.ToShortTimeString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Title = "Odaberite sliku";
                dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
                DialogResult dr = new DialogResult();
                dr = dialog.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    pictureBox3.Image = new Bitmap(dialog.FileName);
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }  
        }

        private void button3_Click(object sender, EventArgs e)
        {
            con.OpenConnection2();
            string query2 = "update tabla set (Slika) values (@Blob)";
            cmd.Connection = Connectioncl.connection2;
            cmd.CommandText = query2;
            cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
            cmd.ExecuteNonQuery();
            MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
            pictureBox2.Image = pictureBox3.Image;
            this.Refresh();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (panel3.Visible = !panel3.Visible)
            {
                panel3.Visible = panel3.Visible;
            }
            else if(panel3.Visible = panel3.Visible)
            {
                panel3.Visible = !panel3.Visible;
            }
        }
    }
}

Thanks for any help!!

UPDATE

So I have decided to insert full data and image directly to table in phpmyadmin and when I entered credentials no errors were showing.

It just seems to be an error while converting to blob while updating the table, now if someone can help me with this i'm pretty new to C# and MySQL especially. [1]: https://i.stack.imgur.com/KUK7a.png

UPDATE #2

I have changed mstr.GetBuffer() to mstr.GetArray(), also I added few lines to code and there are no more errors at saving picture, but I still have problem when it gets saved its corrupted or it just doesn't convert correctly.

When image gets uploaded it doesn't take nearly as much memory as same image i inserted directly into the table which had no problem loading into program.

So now it's just problem converting to binary, guess, any help is appreciated!

This is how code looks after I added couple lines to save button:

private void button3_Click(object sender, EventArgs e)
        {
                byte[] ImageData;
                FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                ImageData = br.ReadBytes((int)fs.Length);
                br.Close();
                fs.Close();  

                con.OpenConnection2();
                string query2 = "update tabla set Slika = '" + ImageData + "' where ID = '" + ID + "'";
                cmd.Connection = Connectioncl.connection2;
                cmd.CommandText = query2;
                cmd.Parameters.AddWithValue("Slika", ImageData);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Refresh();
                con.CloseConnection2();   
        }

I am happy to say that the problem has been fixed, it was indeed problem with saving picture to the database.

The problem was that I had to add parameter MySqlDbType.Blob like so:

cmd.Parameters.Add("@Slika", MySqlDbType.Blob);

And then I had to give that parameter the picture, like so:

cmd.Parameters["@Slika"].Value = ImageData;

Easy as that, feels much more rewarding when you solve the problem yourself:D

I will post the whole code so if someone wants to use it feel free.

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;

namespace Maturski_Rad_1
{
    public partial class Form2 : Form
    {
        Connectioncl con = new Connectioncl();
        MySqlCommand cmd = new MySqlCommand();
        string ID = Form1.id;
        string fname;

        public Form2()
        {
            InitializeComponent();
        }

        public Image displayImage(byte[] slika)
        {

            MemoryStream mstr = new MemoryStream(slika);
            return Image.FromStream(mstr);
        }  

        private void Form2_Load(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = Form1.id; //just to check if its the correct ID
                con.OpenConnection();
                label1.Text = Form1.ime;
                label2.Text = Form1.prezime;
                timer1.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

                try { 
                string query = "select Slika,ID from tabla where ID='" + ID + "'";
                cmd.Connection = Connectioncl.connection;
                cmd.CommandText = query;
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    pictureBox2.Image = displayImage((byte[])dr["Slika"]);

                }
                dr.Close();
                con.CloseConnection();
            }
            catch
            {
                MessageBox.Show("Error: Profilna slika nije pronadjena!");
            }
            
        }


        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void panel1_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("Vas ID je: " + Form1.id, panel1);
            toolTip1.UseFading = true;
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label4.Text = DateTime.Now.ToShortTimeString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Title = "Odaberite sliku";
                dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
                DialogResult dr = new DialogResult();
                dr = dialog.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    pictureBox3.Image = new Bitmap(dialog.FileName);
                    fname = dialog.FileName; 
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }  
        }

        private void button3_Click(object sender, EventArgs e)
        {
                byte[] ImageData;
                FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                ImageData = br.ReadBytes((int)fs.Length);
                br.Close();
                fs.Close();  

                con.OpenConnection2();
                string query2 = "update tabla set Slika= @Slika where ID = '" + ID + "'";
                cmd.Connection = Connectioncl.connection2;
                cmd.CommandText = query2;
                cmd.Parameters.Add("@Slika", MySqlDbType.Blob);
                cmd.Parameters["@Slika"].Value = ImageData;
                cmd.ExecuteNonQuery();
                MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                con.CloseConnection2();
                pictureBox2.Image = pictureBox3.Image;
            
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            pictureBox3.Image = pictureBox2.Image;

            if (panel3.Visible = !panel3.Visible)
            {
                panel3.Visible = panel3.Visible;
            }
            else if(panel3.Visible = panel3.Visible)
            {
                panel3.Visible = !panel3.Visible;
            }
        }
    }
}

Enjoy!

PS. Slika or @Slika means image in my language, its just that I called my image column in the database like that.

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