简体   繁体   中英

How do I upload images to the SQLite database, via a dialog box, and output the image to XAML?

     private void Button_Foto_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();// создаем диалоговое окно
             openFile.ShowDialog();// открываем окно
             string FileName = openFile.FileName;// берем полный адрес картинки
             imgPath = openFile.FileName; // записываем в переменную путь к изображению
             textBoxImg.Text = FileName; // выводим в текстовом поле путь к изображению (для наглядности)
            //InitVariable();
            if (textBoxImg.Text == "") // если не указан путь к изображению, то...
                return; // прекратить выполнение
            // Конвертируем изображение в байты byte[]
            byte[] _imageBytes = null;
            FileInfo _imgInfo = new FileInfo(imgPath); // загрузим изображение
            long _numBytes = _imgInfo.Length; // вычислим длину
            FileStream _fileStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read); // откроем изображение на чтение
            BinaryReader _binReader = new BinaryReader(_fileStream);
            _imageBytes = _binReader.ReadBytes((int)_numBytes); // изображение в байтах

            imgFormat = Path.GetExtension(imgPath).Replace(".", "").ToLower(); // запишем в переменную расширение изображения в нижнем регистре, не забыв удалить (Replace) точку перед расширением
            imgName = Path.GetFileName(openFile.FileName).Replace(Path.GetExtension(imgPath), ""); // запишем в переменную имя файла, не забыв удалить (Replace) расширение с точкой

            // записываем информацию в базу данных
            using (SQLiteConnection Connect = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;"))
            {
                string commandText = "INSERT INTO " + db.AppStaffs + " ([image], [image_format], [image_name]) VALUES(@image, @format, @name)";
                SQLiteCommand Command = new SQLiteCommand(commandText, Connect);
                Command.Parameters.AddWithValue("@image", _imageBytes);
                Command.Parameters.AddWithValue("@format", imgFormat);
                Command.Parameters.AddWithValue("@name", imgName);                
                MessageBox.Show("Изображение добавлено в базу данных");
        
        }
        }

At the moment I am using the code to upload the image to the database, but it does not load, it loads by clicking on the button and selecting from the dialog box, I select, upload, gives a message that everything is fine, is it possible to save the image without splitting into arrays and is it possible to make the code easier without splitting into arrays? Both output and load using a single variable

You are not using executenonquery method. so the queries you wrote will not work. The message appears after you have completed your work.

Command.ExecuteNonQuery();

Use this code it will work.

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