Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I want to save image(bmp/jpg) in sql server 2005.
I have made DSN for database;
Table2(Name nvarchar(20),UserImage varbinary(max))
image is on PictureControl in mfc.
I have made connection successfully.
C++
void CSaveImageDlg::OnBnClickedButton1()
{
	try
	{
		CDatabase m_database;
		CRecordset m_recordset;
		bool p=m_database.Open(_T("Dermalog2"),0,0,_T("ODBC;"),0);//_T("ODBC;")
		m_recordset.m_pDatabase = &m_database; //tell CRecordset where to find the database
		m_recordset.Open(AFX_DB_USE_DEFAULT_TYPE,_T("select * from Table1"),CRecordset::appendOnly);
		//ASSERT(m_recordset.Open(AFX_DB_USE_DEFAULT_TYPE,_T("select * from Table1"),CRecordset::appendOnly));
		HBITMAP h_bit=m_Image.GetBitmap();
		CLongBinary clb;
		clb.m_hData = h_bit;
		clb.m_dwDataLength = ::GlobalSize(h_bit);		
		CBitmap bmp; 
		bmp.LoadBitmap (IDC_Image);
		//Get the number of the selected records
		long reCount=m_recordset.GetRecordCount();
		if(m_recordset.CanAppend())
		{
			m_recordset.AddNew();
			//m_recordset.SetFieldValue(_T("Name","UserImage"),"imran",clb);//Write our COleVariant to the table
			m_database.ExecuteSQL(_T("insert into Table1 values('khan',clb)"));
			//m_recordset.pdb.ExecuteSQL(_T("insert into Table1 values('khan',clb)"));
			m_recordset.Update();
		}
		m_recordset.Close();
		m_database.Close();
	}
	catch(CDBException* ex)
	{

	}	
}

m_recordset.CanAppend() function dioes not work.
What should I do next?
Posted
Updated 10-Feb-13 20:44pm
v2

1 solution

You could achieve this using custom recordset.
1. Create your own class inherited from CRecordset.
2. Put to public a class members like the following:
C++
public:
    LONG a;
    CLongBinary b;
    CString c;
    BOOL d;
//etc...

3. Assign a number of columns in constructor by defining m_nFields variable.
4. Implement data exchange between fields of data base with class members by defining DoFieldExchange.
C++
VOID MyRecordset::DoFieldExchange( CFieldExchange *ex ){
    ex->SetFieldType(CFieldExchange::outputColumn);
    RFX_Long( ex, "db_field_a", this->a );
    RFX_LongBinagy( ex, "db_field_b", this->b );
// ...
}

5. Open your recordset (as you actually did with CRecordset object) with any query to target table
6. Create a new record with AddNew() method
7. Assign your long binary data member with BYTE array and other members with respective values
8. Update your recordset.
These articles might help:
http://msdn.microsoft.com/en-us/library/s55kt8s3(v=vs.71).aspx[^]
http://msdn.microsoft.com/en-us/library/yd6x6wbd(v=vs.71).aspx[^]

http://msdn.microsoft.com/en-us/library/czxt1e3z.aspx[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900