I have an Access .mdb database and I want to insert an image from an application developed in visual C# 2010. Pictures are stored in the database in the field of OLE-object.
After adding images directly in Access they are stored in the format of an Bitmap Image. These pictures can be opened in Access with a double-click.
I have the following code:
OdbcConnection Connection = new OdbcConnection();
...
sql = "INSERT INTO film (poster) VALUES (" ' " + Image.FromFile(textBox8.Text) + " ' ");";
//texbox are stored the picture name
OdbcCommand Command = new OdbcCommand(sql, Connection);
Command.ExecuteNonQuery();
The code works well, but Access stores the picture as binary data and it cannot be opened again in Access. Please tell me how to insert the image as a Bitmap Image. Thanks.
This is a somewhat unusual request. Most people asking about OLE imbedded images in Access are asking about how to convert them from OLE objects into raw binary data, not the other way around. Current versions of Access have features like the Image control that can display bitmap images without having to deal with the complications of OLE "wrappers" being added to the object data.
Still, here is one way to do what you requested. It uses an Access.Application object, so Access must be installed on the machine for this to work. It also requires a Form inside the Access database where
the form itself is bound to the table containing the OLE image field you want to insert,
the only control on the form is a Bound Object Frame, bound to the OLE field.
The sample code also assumes that the table being updated has a numeric primary key field named [ID].
private void button1_Click(object sender, EventArgs e)
{
// test data
int recordIdToUpdate = 15;
string bmpPath = #"C:\Users\Gord\Pictures\bmpMe.bmp";
var paths = new System.Collections.Specialized.StringCollection();
paths.Add(bmpPath);
Clipboard.SetFileDropList(paths);
// COM Reference required:
// Microsoft Access 14.0 Object Library
var accApp = new Microsoft.Office.Interop.Access.Application();
accApp.OpenCurrentDatabase(#"C:\Users\Public\Database1.accdb");
accApp.DoCmd.OpenForm(
"PhotoForm",
Microsoft.Office.Interop.Access.AcFormView.acNormal,
null,
"ID=" + recordIdToUpdate);
accApp.DoCmd.RunCommand(Microsoft.Office.Interop.Access.AcCommand.acCmdPaste);
accApp.DoCmd.Close(
Microsoft.Office.Interop.Access.AcObjectType.acForm,
"PhotoForm",
Microsoft.Office.Interop.Access.AcCloseSave.acSaveNo);
accApp.CloseCurrentDatabase();
accApp.Quit();
this.Close();
}
private string ImageToBase64String(Image image)
{
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, image.RawFormat);
return Convert.ToBase64String(stream.ToArray());
}
}
private void SaveButton()
{
string Pic = ImageToBase64String(PicBox.Image);
OleDbCommand PicSave = new OleDbCommand("INSERT INTO Picture(ID,PICTURE)VALUES(" + PicId.Text + ",'" + Pic + "')", con);
con.Open();
var SaveValue = PicSave.ExecuteNonQuery();
if (SaveValue > 0)
{
MessageBox.Show("Record Saved", "Information");
ValueClear();
}
else
MessageBox.Show("Rocord Not Saved", "Erro Msg");
con.Close();
}
Related
I am developing a system that will import and export a data from Excel into a SQL Server database. I already done in exporting, my problem is in importing the template that I will import is different template that I exported. I know the code about importing because I learned it in google, but in my problem is, I can't get what I need. So allow me to show a screenshot about the template in my Excel.
That's the template, and my database design is like this:
So the PODATE and PORECEIVEDDATE there in database is equal to the PO DATE below in Excel and DELIVERYDATE is equal to ETD in Excel.
As of now I have a code here that will get only the above template and it will not get the whole data in Excel.
Here is my code:
public void ImportDataFromExcel(string excelFilePath)
{
string ssqltable = "tmp_100_POEntry_SF_sample";
//string myexceldataquery = "select PONO,PODATE,PORECEIVEDDATE,DELIVERYDATE,PARTCODE,QUANTITY,UNITCOST,TOTALAMOUNT,STOCKS,INCHARGE,CLIENT from [Sheet1$]";
string myexceldataquery = "select [PO NO],[PART CODE],QUANTITY,[UNIT COST],[TOTAL AMOUNT],STOCKS,[IN CHARGE],CLIENT from [Sheet1$]";
try
{
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + excelFilePath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(Common.connectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(Common.connectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
}
catch (Exception ex)
{ throw ex; }
}
That code is really have an error if I add the PODATE, PORECEIVEDDATE and DELIVERDATE. All I just want is to get the 3 remaining parameters value from Excel into the database.
I don't want to change the template in Excel because of some reason.
Please I badly need your help guys. I really appreciate it.
Suppose, We have two databases , db_1 and db_2.
There are a table named 'T1' in db_1, now,I need a package in SSIS which will ask for names sql objects.If I choose 'T1',the data will be transfered to db_2.
I dont know if it is possible.
Generally SSIS is not meant to be used in an Interactive mode. Any user input is either introduced as a config setting or environment variable or as values in some other table.
Alternately, you can also prompt for and capture input values outside of the SSIS Package and then execute the SSIS Package, in C# or ASP.Net or any other interactive platform.
That said, if you must prompt for input and use it, the way to do it is by instantiating and displaying a Form in a Script Component.
Create a variable at the appropriate scope called tableName in the package. Then use the code below (modify it as needed) to set the tableName variable's value to whatever the user enters. Finally, use the same tableName variable in your control flow to copy the data from.
System.Windows.Forms.Form frm = new Form();
TextBox = new TextBox();
Button submitButton = new Button();
public void Main()
{
submitButton.Text = "Enter source table name";
submitButton.Width = 300;
submitButton.Height = 80;
submitButton.Click += new EventHandler(submitButton_Click);
tableNameTextBox.Name = "Input";
frm.Controls.Add(tableNameTextBox);
frm.Controls.Add(submitButton);
frm.ShowDialog();
MessageBox.Show(Dts.Variables["tableName"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
void submitButton_Click(object sender, EventArgs e)
{
Dts.Variables["tableName"].Value = tableNameTextBox.Text;
frm.Close();
}
Ref: https://stackoverflow.com/a/4121557/325521
I have convert an image to be saved in SQL Server Database as Binary with column name as "img". I have PictureBox1 ready to show the image.
Now I want to import the binary data back into image, and I'm trying this code in VB.net for example:
Dim queries As String
queries = "SELECT * from StudentData where Std_fname='" & ComboBox1.Text & "'"
Dim com As New SqlCommand(queries, sqlconn)
sqlconn.Open()
Dim ds As New SqlDataAdapter(queries, sqlconn)
Dim dr As SqlDataReader
dr = com.ExecuteReader()
While dr.Read
Std_fnameTextBox.Text = dr("Std_fname")
Std_lnameTextBox.Text = dr("Std_lname")
AgeTextBox.Text = dr("age")
AddressTextBox.Text = dr("address")
StateTextBox.Text = dr("state")
CityTextBox.Text = dr("city")
CountryTextBox.Text = dr("country")
Ic_passportTextBox.Text = dr("ic_passport")
DobDateTimePicker.Text = dr("dob")
PictureBox1.Image = dr("img") 'Here is the problem. If I run it, it ask me to convert Binary to Image first.
End While
sqlconn.Close()
The problem is, I don't know how to convert binary to image in this situation. And yes, I've been googling for it, but can't seem to get the right answer.
dr("img") returns either DBNull.Value, or a byte[]. You can use the stream overload of the Bitmap constructor to load this. In C# (should be easy to translate to VB), you can do it like this:
var imageData = (byte[])dr["img"];
using (var ms = new MemoryStream(imageData))
{
var bmp = new Bitmap(ms);
// Work with bmp
}
As Mark correctly noted, you're supposed to keep the stream open for the whole life-time of the Bitmap - this is actually a bit trickier than it seems, because the Bitmap doesn't even keep a reference to the stream.
The easiest way to handle this is to clone the bitmap after you create it, to remove the dependency on the stream. Unless you can do whatever work you need to do within the using - unlikely if you want to display it in a PictureBox.
You can also use ImageConverter.ConvertFrom directly, but all it does is create the MemoryStream if used on raw byte[] data :)
I created a Windows Form, with a ComboBox, and a Local Database in Visual Studio 2010. The database has a table with a column whose rows I want to list in the combo box. How can I achieve this?
I tried adding a data source with the column I am interested in through the IDE, but it did not work.
I created a Windows Forms Application with a Windows Form containing a ComboBox.
I created a Local Database containing a Table with a single column and three test rows.
I added a data source containing the column I am interested in.
Finally, I bound the combo box to the data source, but the result is strange.
This is the raw code to accomplish what you are asking:
string strCmd = "";
string strConn = "";
SqlConnection sqlConn = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand(strCmd, sqlConn);
SqlDataReader sqlRdr = new SqlDataReader();
sqlConn.Open();
if (comboBox1.Items.Count > 0)
comboBox1.Items.Clear();
sqlRdr = sqlCmd.ExecuteReader();
while (sqlRdr.Read())
comboBox1.Items.Add(sqlRdr[0].ToString());
sqlRdr.Close();
sqlConn.Close();
There are a few things you will need to wire-up first though. The first one is this:
string strCmd = ""; // Insert your SQL statement here.
Second:
string strConn = ""; // Your db connection string goes here.
Thirdly:
if (comboBox1.Items.Count > 0) // You don't have to use this. It just checks to see
comboBox1.Items.Clear(); // if there is anything in the combobox and clears it.
Lastly, since you are making something that handles interactions between your form and a database, I strongly suggest that you use SqlParameters to prevent SQL Injection attacks.
I am a beginner to programming and I am trying to make a program that tracks my jogging data in WPF. I set up a listbox that has databinding with my compact sql database where my info gets logged to. While I am in visual studio it works as it should, but when I publish the program, the listbox will no longer display the proper info from the database. It starts fresh all over again each time I start a new session of the program. I know that the info is in the database because I have charts that will properly show all the latest logged data. The listbox, however, will only show data logged during that current session. When I close down the program and reopen, the data from my previous session is not displayed in the listbox anymore.
My code looks like this:
runDataDataSet1 ds;
runDataDataSet1TableAdapters.runDataTableTableAdapter dt;
weightDataSet wds;
weightDataSetTableAdapters.weightTableTableAdapter wdt;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ds = ((runDataDataSet1)(this.FindResource("runDataDataSet1")));
dt = new runDataDataSet1TableAdapters.runDataTableTableAdapter();
dt.Fill(ds.runDataTable);
CollectionViewSource cvs = ((CollectionViewSource)(this.FindResource("runDataTableViewSource")));
cvs.View.MoveCurrentToFirst();
wds = ((weightDataSet)(this.FindResource("weightDataSet")));
wdt = new weightDataSetTableAdapters.weightTableTableAdapter();
wdt.Fill(wds.weightTable);
CollectionViewSource wcvs = ((CollectionViewSource)(this.FindResource("weightTableViewSource")));
wcvs.View.MoveCurrentToFirst();
To submit the data I have this code for when the submit button is pushed:
double pace = runData.runPace(runData.milesRun, runData.timeRun);
double pace2 = Math.Round(pace, 1);
double milesDuration = Math.Round((runData.mileDuration(runData.milesRun, runData.timeRun)), 1);
paceTextBox.Text = ((milesDuration) + " min mile");
//UPDATE DATABASE
string myConnectionString = #"Data Source=C:\Users\zfam\My Projects\programming\visual studio\XTrakker\XTrakker\runData.sdf";
string mySelectQuery = "SELECT [int], [runDate], [runDist], [runTime], [runPace] FROM [runDataTable] order by [int] desc";
DataRow dr = ds.Tables["runDataTable"].NewRow();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(mySelectQuery, myConnectionString);
dr["runDate"] = date;
dr["runDist"] = distData;
dr["runTime"] = timeData;
dr["runPace"] = milesDuration;
ds.Tables["runDataTable"].Rows.Add(dr);
SqlCeCommandBuilder projectBuilder = new SqlCeCommandBuilder(adapter);
DataSet newSet = ds.GetChanges(DataRowState.Added);
adapter.Update(newSet, "runDataTable");
adapter.Dispose();
Again, while I am in visual studio and I run the program, this all works as it should. Once I publish, the listbox will only show the data from the current session, even the the actual database file is being updated. Perhaps I am doing this all wrong? Any thoughts?
Hard to say, but I am a bit confused about this line:
string myConnectionString = #"Data Source=C:\Users\zfam\My Projects\programming\visual studio\XTrakker\XTrakker\runData.sdf";
Look like you hardcode your datasource provider. Are you sure you use the same datasource in visual studio, and when you publish your app?
Maybe the datasource is re-created at each execution, which could explain why you have always new data.