powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / ADO.NET, LINQ, Entity Framework, NHibernate, DAL, ORM [игнор отключен] [закрыт для гостей] / Проблема с работой BLOB и Access.
6 сообщений из 6, страница 1 из 1
Проблема с работой BLOB и Access.
    #35045344
Sharki
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Застрял ни как не получается работать с image.
Пытаюсь добавить картинку в Access, вроде все срабатывает,а вот дальше ни как.Как например по ID вытаскивать данные и соответствующую картинку.Посмотрел весь форум и в google поискал но что то ни как.Подскажите плиззз.Код Прилагается.Зарание огромное спасибо.
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
// **** Read Image from Filesystem and add it to the Database. 
		public void AddEmployee(
			string UserID,
			string UserName,
			string UserEmail,
            string UserDescription,
			//DateTime hireDate,
			//int preportsTo,
			string photoFilePath)
		{

			// Read Image into Byte Array from Filesystem
			byte[] photo = GetPhoto(photoFilePath);

			// Construct INSERT Command
			OleDbCommand addEmp = new OleDbCommand(
				"INSERT INTO Users ("+
                "UserID,UserName,UserEmail,UserDescription,UserPhoto) " +
                "VALUES(@UserID,@UserName,@UserEmail,@UserDescription,@UserPhoto)", conn); //@ReportsTo ReportsTo

            addEmp.Parameters.Add("@UserID", OleDbType.VarChar,  20 ).Value = UserID;
            addEmp.Parameters.Add("@UserName", OleDbType.VarChar,  20 ).Value = UserName;
            addEmp.Parameters.Add("@UserEmail", OleDbType.VarChar,  20 ).Value = UserEmail;
            addEmp.Parameters.Add("@UserDescription", OleDbType.VarChar,  20 ).Value = UserDescription;
			//addEmp.Parameters.Add("@ReportsTo", SqlDbType.Int).Value          = preportsTo;
			addEmp.Parameters.Add("@UserPhoto",     OleDbType.Binary, photo.Length).Value = photo;

			// Open the Connection and INSERT the BLOB into the Database
			conn.Open();
			addEmp.ExecuteNonQuery();
			conn.Close();
		}

		// **** Read Image into Byte Array from Filesystem
		public static byte[] GetPhoto(string filePath)
		{
			FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
			BinaryReader br = new BinaryReader(fs);

			byte[] photo = br.ReadBytes((int)fs.Length);

			br.Close();
			fs.Close();

			return photo;
		}

		// **** Read BLOB from the Database and save it on the Filesystem
		public void GetEmployee(string UserID,string UserName)
		{
			OleDbCommand getEmp = new OleDbCommand(
                "SELECT  UserPhoto " +
				"FROM Users "+
                "WHERE UserID = @UserID " +
                "AND UserName = @UserName", conn);

            getEmp.Parameters.Add("@UserID", OleDbType.VarChar,  20 ).Value = UserID;
            getEmp.Parameters.Add("@UserName", OleDbType.VarChar,  20 ).Value = UserName;

			FileStream fs;                          // Writes the BLOB to a file (*.bmp).
			BinaryWriter bw;                        // Streams the BLOB to the FileStream object.
			int bufferSize =  100 ;                   // Size of the BLOB buffer.
			byte[] outbyte = new byte[bufferSize];  // The BLOB byte[] buffer to be filled by GetBytes.
			long retval;                            // The bytes returned from GetBytes.
			long startIndex =  0 ;                    // The starting position in the BLOB output.
			string emp_id = "";                     // The employee id to use in the file name.

			// Open the connection and read data into the DataReader.
			conn.Open();
			OleDbDataReader myReader = getEmp.ExecuteReader(CommandBehavior.SequentialAccess);

			while (myReader.Read())
			{
				// Get the employee id, which must occur before getting the employee.
				emp_id = myReader.GetInt32( 0 ).ToString();

				// Create a file to hold the output.
                fs = new FileStream("Users" + UserID + ".bmp", 
					                FileMode.OpenOrCreate, FileAccess.Write);
				bw = new BinaryWriter(fs);

				// Reset the starting byte for the new BLOB.
				startIndex =  0 ;

				// Read the bytes into outbyte[] and retain the number of bytes returned.
				retval = myReader.GetBytes( 1 , startIndex, outbyte,  0 , bufferSize);

				// Continue reading and writing while there are bytes beyond the size of the buffer.
				while (retval == bufferSize)
				{
					bw.Write(outbyte);
					bw.Flush();

					// Reposition the start index to the end of the last buffer and fill the buffer.
					startIndex += bufferSize;
					retval = myReader.GetBytes( 1 , startIndex, outbyte,  0 , bufferSize);
				}

				// Write the remaining buffer.
                bw.Write(outbyte,  0 , (int)retval);
				bw.Flush();

				// Close the output file.
				bw.Close();
				fs.Close();
			}

			// Close the reader and the connection.
			myReader.Close();
			conn.Close();
		}

		private void btnAddEmp_Click(object sender, System.EventArgs e)
		{
            //DateTime hireDate = DateTime.Now;
            AddEmployee(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, _fname);//Convert.ToInt16(textBox4.Text)
			statusBar.Text = "Employee added to the Database";
            pbxPhoto.Hide();
            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
            textBox4.Clear();
            //textBox5.Clear();
            
		}

		private void btnGetEmp_Click(object sender, System.EventArgs e)
		{
            pbxPhoto.Show();
			GetEmployee(textBox1.Text,"");
			statusBar.Text = "Employee saved to Filesystem";
		}

		private void btnLoadPhoto_Click(object sender, System.EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();

			dlg.Title = "Open Photo";
			dlg.Filter = "Windows Bitmap Files (*.bmp)|*.bmp"
				+ "|All files (*.*)|*.*";

			if (dlg.ShowDialog() == DialogResult.OK)
			{
				try
				{
					pbxPhoto.Image = new Bitmap(dlg.OpenFile());
					_fname = dlg.FileName;
				}
				catch (Exception ex)
				{
					MessageBox.Show("Unable to load file: " + ex.Message);
				}
			}

			dlg.Dispose();
		}
...
Рейтинг: 0 / 0
Проблема с работой BLOB и Access.
    #35048251
Sharki
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
с этим делом вродебы разобрался.Теперь проблемма в следующем,значит имеется две формы.Первая главная(на ней находится dataGridView1 и прикрутил сюдаже DataBindings),вторая форма new worker(на ней имеются все текст боксы и пиктчер бокс).Вродебы все просто но вот застрял на этом.Во время когда заносятся данные в базу данных если я не указываю путь к фотографии то вылетает ошибка на этой строке :

byte[] imageData = ReadFile(txtImagePath.Text);


Текст такой: System.ArgumentException: The path is not of a legal form.
Подскажите плизз как это обойти чтоб была возможность сохронять данные нового рабочего,а после можно будет добавить фото.

И еще одна проблемма.Например просто как вариант
нажимаю на кнопку захожу на форму(new worker)не чего не изменяю закрываю форму и вылетает ошибка на главной форме:
System.ArgumentException: This causes two bindings in the collection to bind to the same property.
Parameter name: binding

не понимаю откуда берется второй binding.
Подскажите плиззз,зарание огромное спасибо.
...
Рейтинг: 0 / 0
Проблема с работой BLOB и Access.
    #35066144
Sharki
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Проблемма следующая.
Есть DataGridView загружаю данные,данные бандятся,затем есть txt_Finde ввожу информацию по которой происходит сортировка в DataGridView.Затем хочу удалить эту строку :
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
private void btn_Delete_Click(object sender, EventArgs e)
        {
            try
            {
                 this.oleDbConnection = new OleDbConnection();

                oleDbConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\Users_DB.mdb";

                
                
                this.adapter1.DeleteCommand = new OleDbCommand();
                this.adapter1 = new OleDbDataAdapter();

                this.adapter1.DeleteCommand.Connection = oleDbConnection;               
                
                
                this.adapter1.DeleteCommand.CommandText =
                 " Delete * from Users where WorkNumber = " + this.txt_Find.Text;         
                           
                this.oleDbConnection.Open();

                this.adapter1.DeleteCommand.ExecuteNonQuery();

                this.oleDbConnection.Close();

                MessageBox.Show("Record deleted Successfully \n \nITEM CLEAR !!!", " Warning !!! Warning !!! Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);  //inform the user
                this.Close();


            }
            
            catch (System.Data.OleDb.OleDbException exp)
            {

                MessageBox.Show(exp.ToString());
            }
            finally
            {
                //close the connection
                this.oleDbConnection.Close();
            }


        }
и вот сдесь:
this.adapter1.DeleteCommand.Connection = oleDbConnection;
выподает такая ошибка :
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object.

Подскажите что не так,зарание спасибо.
...
Рейтинг: 0 / 0
Проблема с работой BLOB и Access.
    #35067247
Sharki
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Путем долгих эксперементов дошол до этой функции:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //Get image data from gridview column.
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["Photo"].Value;

                //Initialize image variable
                Image newImage;
                //Read image data into a memory stream
                using (MemoryStream ms = new MemoryStream(imageData,  0 , imageData.Length))
                {
                    ms.Write(imageData,  0 , imageData.Length);

                    //Set image variable value using memory stream.
                    newImage = Image.FromStream(ms, true);
                }

                //set picture
                pictureBox1.Image = newImage;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
если я её убераю то фото не появляется,хотя бандинг работает.Еще пытался сделать с помощю компонента бандинг сорс.На этой строке:
Код: plaintext
byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["Photo"].Value;
вылетает ошибка что такой колонки (Photo)он не видит.Что за ....Подскажите в чем проблема.
...
Рейтинг: 0 / 0
Проблема с работой BLOB и Access.
    #35069719
Фотография Strassebahn
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
храни картинки отдельном каталоге, а в базе сохраняй только путь и имена файлов
...
Рейтинг: 0 / 0
Проблема с работой BLOB и Access.
    #35070655
Sharki
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
всем спасибо ,вопрос снят.Спасибо.
...
Рейтинг: 0 / 0
6 сообщений из 6, страница 1 из 1
Форумы / ADO.NET, LINQ, Entity Framework, NHibernate, DAL, ORM [игнор отключен] [закрыт для гостей] / Проблема с работой BLOB и Access.
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]