I am working on oracle 11g. I created a table which have 3 columns, SQL for create table is
create table blobvideo(fileid int,filename varchar2(100), filedata blob);
My code to insert video in that table is
FileInfo fi = new FileInfo("C:\videoPath.mp4");
FileStream fs = new FileStream(videoFilePath, FileMode.Open, FileAccess.Read);
byte[] fileToByte = new byte[fs.Length];
fs.Read(fileToByte, 0, Convert.ToInt32(fs.Length));
String strSQL = "INSERT INTO blobvideo (FileId,filename,FILEDATA) VALUES (1,'" + fi.FullName + "',:TEXT_DATA)";
OracleParameter parmData = new OracleParameter();
parmData.Direction = ParameterDirection.Input;
parmData.OracleDbType = OracleDbType.Blob;
parmData.ParameterName = "TEXT_DATA";
parmData.Value = fileToByte;
OracleCommand cm = new OracleCommand();
cm.Connection = myConnection;
cm.Parameters.Add(parmData);
cm.CommandText = strSQL;
myConnection.Open();
cm.ExecuteNonQuery();
myConnection.Close();
My code to get BLOB is
OracleCommand ocmd1 = new OracleCommand("select * from blobfile ", myConnection);
myConnection.Open();
OracleDataReader rds = ocmd.ExecuteReader();
rds.Read();
OracleBlob newBlob = rds.GetOracleBlob(2);
Insertion is working well, but my question is how can i get that video and how can i play that video in windows media player or vlc or any other video player that works with C#.
Related
I have sqlite database who store Arabic text in varchar field
I used this code,but when try to read the value question mark is appear instead character
SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt FROM tblQTxt'", con);
con.Open();
SQLiteDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr["Qtxt"].ToString();
dr.Close();
con.Close();
I used "DB Browser for SQLite" fro opening database
when try to view field as binary mode and then export as text I will see the true character
how can read this filed truly?
SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt2 FROM tblQTxt where Sore='1' and Aye='1'", con);
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter(cmd);
DataSet dSet = new DataSet();
dAdapter.Fill(dSet);
if (dSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dSet.Tables[0].Rows[0]["Qtxt2"]);
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
StreamReader reader = new StreamReader(ms,Encoding.GetEncoding(1256));
string text = reader.ReadToEnd();
textBox1.Text = text;
}
I have a picturebox on a windows form that gets filled with this command:
pBProcess.ImageLocation = Path.GetDirectoryName(processFile) + "\\" + processes[processStep2Nr] + ".png";
After the images is loaded I'm trying to do two things that both only work after I loaded that image twice.
First thing:
Positioning.CenterHorizontally(pBProcess, pBProcess.Image.Width);
Which does this:
public static void CenterHorizontally(this Control control, int Width)
{
Rectangle parentRect = control.Parent.ClientRectangle;
control.Left = (parentRect.Width - Width) / 2;
}
and the second thing I'm trying to do is to save the image to a SQLDatabase.
cmdLine = "INSERT INTO " + processToSave + " (Picture) VALUES (#Image);";
MemoryStream stream = new MemoryStream();
pBProcess.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] pic = stream.ToArray();
using (SqlCommand sqlCmd = new SqlCommand(cmdLine, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
sqlCmd.ExecuteNonQuery();
}
Boths actions are executed correctly after I load the picturebox.image a second time.
What causes this and how can I fix it?
Edit:
This is how I create the table I want to save the picture to:
//Tabelle wird erstellt und anschließend gefüllt
strInsert = "CREATE TABLE " + processToSave + "(Attributes NVARCHAR(50), Value TINYINT, Picture IMAGE);";
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
sqlCmd.ExecuteNonQuery();
}
strInsert = "INSERT INTO " + processToSave + " (Attributes, Value) VALUES (#Attributes, #Value);";
foreach (ListViewItem item in checkedItems)
{
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Attributes", SqlDbType.NVarChar);
sqlCmd.Parameters["#Attributes"].Value = item.Text;
sqlCmd.Parameters.Add("#Value", SqlDbType.Int);
sqlCmd.Parameters["#Value"].Value = Convert.ToInt32(item.SubItems[1].Text);
sqlCmd.ExecuteNonQuery();
}
}
strInsert = "INSERT INTO " + processToSave + " (Picture) VALUES (#Image);";
MemoryStream stream = new MemoryStream();
pBProcess.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] pic = stream.ToArray();
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
sqlCmd.ExecuteNonQuery();
}
And this is how I read the picture from the DB:
MemoryStream stream = new MemoryStream();
strInsert = "SELECT [Picture] FROM " + processToLoad;
SqlCommand sqlCmd2 = new SqlCommand(strInsert, connection);
byte[] image = (byte[])sqlCmd2.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
pBProcess.Image = bitmap;
this is NOT working. But when I create a table in the DB called "Bilder" which has only "Picture" with DBType Image and change the code to this:
strInsert = "INSERT INTO Bilder (Picture) VALUES (#Image);";
MemoryStream stream = new MemoryStream();
pBProcess.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] pic = stream.ToArray();
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
sqlCmd.ExecuteNonQuery();
}
...
MemoryStream stream = new MemoryStream();
strInsert = "SELECT [Picture] FROM Bilder";
SqlCommand sqlCmd2 = new SqlCommand(strInsert, connection);
byte[] image = (byte[])sqlCmd2.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
pBProcess.Image = bitmap;
It actually works. What's wrong in my original code?
I was mixing up two problems here.
The problem with
Positioning.CenterHorizontally(pBProcess, pBProcess.Image.Width);
was fixed by putting this statement into the LoadCompletedEvent of the picturebox.
The second problem was that I actually inserted a lot of rows into my table (attributes + value) and at the end I inserted another row, consisting only of the image. When I read the table looking for the image, I only read the first row (I think) but there was no image to be found. So I changed the code, putting the image into the first row and then changing the commandline:
bool first = true;
foreach (ListViewItem item in checkedItems)
{
if (first)
cmdLine = "INSERT INTO " + processToSave + " (Attributes, Value, Picture) VALUES (#Attributes, #Value, #Image);";
else
cmdLine = "INSERT INTO " + processToSave + " (Attributes, Value) VALUES (#Attributes, #Value);";
using (SqlCommand sqlCmd = new SqlCommand(cmdLine, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Attributes", SqlDbType.NVarChar);
sqlCmd.Parameters["#Attributes"].Value = item.Text;
sqlCmd.Parameters.Add("#Value", SqlDbType.Int);
sqlCmd.Parameters["#Value"].Value = Convert.ToInt32(item.SubItems[1].Text);
if (first)
{
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
first = false;
}
sqlCmd.ExecuteNonQuery();
}
}
First of all I'm using a FileStream with the server. The server is SQL Server express 2014.
I configured the database and table correctly (I hope) and I was able to upload an image as a varbinary, but when I try to download that image I get an error
An invalid parameter was passed to the function.
Here is the database structure
Records(
[id] [uniqueidentifier] ROWGUIDCOL NOT NULL UNIQUE,
[Name] [varchar](64) NULL,
[Clip] [varbinary](max) FILESTREAM NULL,
)
And the code for downloading the image
private object GetTransactionContext()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
cmd.CommandType = CommandType.Text;
cmd.Connection = sql_Connection;
return cmd.ExecuteScalar();
}
private void BeginTransaction()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "BEGIN TRANSACTION";
cmd.CommandType = CommandType.Text;
cmd.Connection = sql_Connection;
cmd.ExecuteScalar();
}
private void CommitTransaction()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "COMMIT TRANSACTION";
cmd.CommandType = CommandType.Text;
cmd.Connection = sql_Connection;
cmd.ExecuteScalar();
}
//Command for reading the data
public async void ReadFromDatabase(string Name)
{
//enter the command parameter
sql_Command_Read.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name;
//open a connection to the server
sql_Connection.Open();
this.BeginTransaction();
//get the path to the BLOB object
string filePath = null;
Object pathObj = sql_Command_Read.ExecuteScalar();
if (DBNull.Value != pathObj)
{
filePath = (string)pathObj;
}
else
{
throw new NotImplementedException();
}
Object obj = this.GetTransactionContext();
byte[] sql_TransactionToken = (byte[])obj;
sql_FileStream = new SqlFileStream(filePath, sql_TransactionToken, FileAccess.ReadWrite, FileOptions.SequentialScan, 0);
byte[] buffer = new byte[(int)sql_FileStream.Length];
sql_FileStream.Seek(0L, SeekOrigin.Begin);
sql_FileStream.Read(buffer, 0, buffer.Length);
File.WriteAllBytes("C:\test.mp4", buffer);
this.CommitTransaction();
}
The content of the command is
sql_Command_Read.CommandText = "SELECT Picture.PathName() FROM Archive.dbo.Records WHERE Name = #Name";
Again I am new to database and sql client programming. Now about the code. The error that I get is on this line:
sql_FileStream = new SqlFileStream(filePath, sql_TransactionToken, FileAccess.ReadWrite, FileOptions.SequentialScan, 0);
and about the parameters here are the values they get:
filePath = "\\\\LAPTOP-PC\\VIDEOPRESENTERDB\\v02-A60EC2F8-2B24-11DF-9CC3-AF2E56D89593\\Archive\\dbo\\Records\\Picture\\C94D4189-9ECF-448B-B05A-ABF9331BF6CE\\VolumeHint-HarddiskVolume2"
obj has 16 numbers ranging from 0 to 255.
I am obviously making a mistake somewhere but I don't know where exactly
I am storing the image from web cam to sql server but unable to retrieve the image back to picture box. Here is code to store image from picture box to sql server.
MemoryStream ms1 = new MemoryStream();
userpic2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
SqlCommand cmd = new SqlCommand("INSERT INTO CustomerDetails(Photo) values (#pic)", con);
cmd.Parameters.AddWithValue("#pic", img_arr1);
cmd.ExecuteNonQuery();
Code to retrieve image from database to picturebox:-
MemoryStream stream = new MemoryStream();
SqlCommand command = new SqlCommand("select Photo from CustomerDetails where Fname='" + Glist.SelectedItem + "'", con);
byte[] image = (byte[])command.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);/// here i am getting error as INVALID PARAMETER
userpic2.Image = bitmap;
byte[] bt;
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=true"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID=2", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
bt = reader["Photo"] as byte[] ?? null;
ImageConverter ic = new ImageConverter();
System.Drawing.Bitmap img = (System.Drawing.Bitmap)ic.ConvertFrom(bt);
pictureBox1.Image = img;
}
}
}
}
SqlCommand cmd = new SqlCommand("select top 1(CMTID),COMMENT,HEADING from FTAB ORDER BY CMTID DESC", conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read() == true)
{
lblHead.Text = sdr["HEADING"].ToString();
lblData.Text = sdr["COMMENT"].ToString();
}
conn.Close();
That is the code for normal data value retrieve from table now I want to get picture from SQL Server that is saved as Binary data that code mention in bottom. So I want to retrieve picture into an Image control of asp.net; please guide me.
if (FileUpload1.HasFile)
{
conn.Close();
String SqlQery;
SqlQery = "select max(CMTID) from FTAB";
SqlCommand cmdid = new SqlCommand(SqlQery, conn);
conn.Open();
MaxID = (int)(cmdid.ExecuteScalar()) + 1;
conn.Close();
byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile myimg = FileUpload1.PostedFile;
myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into FTAB (CMTID, IMAGEDT, COMMENT, DATETM, HEADING) values (#imgid, #image, #comment, #datetm, #heading)", conn);
SqlParameter imgid = new SqlParameter("#imgid",SqlDbType.Int);
imgid.Value = MaxID;
cmd.Parameters.Add(imgid);
SqlParameter uploading = new SqlParameter("#image", SqlDbType.Image);
uploading.Value = img;
cmd.Parameters.Add(uploading);
SqlParameter cmtt = new SqlParameter("#comment", SqlDbType.NVarChar);
cmtt.Value = RadTextBox3.Text;
cmd.Parameters.Add(cmtt);
SqlParameter dttm = new SqlParameter("#datetm", SqlDbType.DateTime);
dttm.Value = DateTime.Now;
cmd.Parameters.Add(dttm);
SqlParameter hhding = new SqlParameter("#heading", SqlDbType.NVarChar);
hhding.Value = RadTextBox8.Text;
cmd.Parameters.Add(hhding);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
lblHead.Text = "Image uploaded";
}
else
{
lblHead.Text = "No file selected";
}
Try this
SqlCommand cmd = new SqlCommand("select IMAGEDT from FTAB", new SqlConnection("your connection string"));
object data = cmd.ExecuteScalar();
byte[] imgBytes = (byte[])data;
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string filePath = Server.MapPath("temp") + "//" + "img"+DateTime.Now.Ticks.ToString()+".png";
FileStream fs = File.Create(filePath);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();
img.ImageUrl = filePath;
But I would say this isn't the best way to do it, you should save your uploaded images as files as in your website and save the path of that file in your database.
yogi's answer is correct in principle, but requires a web server directory "temp" and write access on an IIS directory.
You can also solve the problem using an image handler as explained in another SO question. Database retrieval is done in the same way, but the rendering happens from a stream, rather than a temp file.