Inserting an image into MySQL database using file upload control - asp.net

I would like to insert the image into a MySQL database using the file upload control in Visual Studio. I am using ASP.NET 3.5 and MySQL Community Server with ODBCc and .NET Connectors.

Here some code that will pull the posted file into a byte array. It'll then pass it down to MySQL. Assumes a varbinary column data type. Modify as you need.
if(FileUploadControl.HasFile)
{
try
{
byte[] img = new byte[FileUploadControl.PostedFile.ContentLength- 1];
img = FileUploadControl.FileBytes;
InsertImg(img);
}
catch(Exception ex)
{
}
}
....
public void InsertImg(byte[] img) //untested code
{
using (MySqlConnection conn = new MySqlConnection(connString))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = #"INSERT INTO MyTable(MyImage) VALUES (#Img)";
cmd.Parameters.Add("#Img", System.Data.SqlDbType.VarBinary); //or SqlDbType.Image
cmd.Parameters["#Img"].Value = img;
conn.Open();
cmd.ExecuteNonQuery();
}
}
}

Related

How to get last incremented id in SQL with single query

My requirement I inserted successfully I want to bind last increment id to the root folder file name.id was automatic incremented in SQL. I want to bind last incremented id on that bold part place.
This is my code please help me to solve this problem:
string insert = "insert into Articles values('" + html+ "','" + text + "')";
try
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(#"~\Articles\**ID**.html"), true))
{
file.WriteLine(value.editor); // Write the file.
}
return msg;
}
else
{
return msg1;
}
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
Please note that your code is a security risk as it's vulnerable to sql injection attacks as Sean Lange rightfully wrote in the comments.
Also, the empty catch is a problem as he pointed out. Do yourself a favor and never ever use empty catch blocks.
To get the last generated identity value in the current session you should use Sql Server's SCOPE_IDENTITY() function.
Note that if you have an instead of insert trigger on the table SCOPE_IDENTITY() will not give you the correct value.
Your code should look something like this:
string insert = "insert into Articles values(#html, #text); select scope_identity()";
using (var con = new SqlConnection("<YOUR CONNECTION STRING HERE>"))
{
using (var cmd = new SqlCommand(insert, con))
{
cmd.Parameters.Add("#html", SqlDbType.NVarChar).Value = html;
cmd.Parameters.Add("#text", SqlDbType.NVarChar).Value = text;
try
{
con.Open();
var databaseId = cmd.ExecuteScalar();
if (databaseId is int)
{
using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(string.Format(#"~\Articles\{0}.html", databaseId)), true))
{
file.WriteLine(value.editor); // Write the file.
}
return msg;
}
else
{
return msg1;
}
}
catch (Exception ex)
{
// Write to log, show an error message to the user
}
}
}

Reading the Excel sheeet from Asp.net?

Getting error while reading the excel sheet from the local drive. I am using asp.net to read the excel sheet. My error:
The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
protected void btnup_Click(object sender, EventArgs e)
{
string Extension = Path.GetExtension("Book1.xlsx");
string FolderPath = #"D:/Book1.xlsx";
Import_To_Grid(FolderPath, Extension);
}
private void Import_To_Grid(string FilePath, string Extension )
{
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"] .ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"] .ConnectionString;
break;
}
using (OleDbConnection conn = new OleDbConnection(conStr))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string firstSheetName = sheetsName.Rows[0][2].ToString();
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName);
OleDbDataAdapter ada = new OleDbDataAdapter(sql, conStr);
DataSet set = new DataSet();
ada.Fill(set);
}
}
I am getting error at conn.Open().
This error may happen because you are opening that excel file by using MS Office or another process is opening your excel file.
i got the solution for my question. Actually i did some thing wrong in connection string in connection string at source i not given the path, that is the reason it is throwing error.

trouble using httphandler to retrieve image url

I am trying to write a httphandler to retrieve image url and later display it on a image control i am using this code but its not working
OleDbConnection mDB = new OleDbConnection(
ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString);
mDB.Open();
OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
context.Response.BinaryWrite((byte[])rdr[0]);
mDB.Close();
context.Response.End(); */
sorry that i caused a confusion earlier in the SELECT statement the pProductId does not contain the URL of the image instead pProductImage is the field that contain the URL. i am using the Id to identify which image to display accordingly.
this is my expected output:
<img src="ImgHandler.ashx?pProductId=2" alt="" />
i cant place image this is the link to my error msg:http://imgur.com/Cix67
This is a two steps answer.
In the page, you can do something like this:
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
using (OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.Write("<img src=\"ImgHandler.ashx?pProductId=");
context.Response.Write((int)rdr[0]); // I suppose pProductId is an int, adapt accordingly
context.Response.Write("\" />");
}
}
}
and in the HTTP handler implicitly triggered, something like this:
public class MyHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
// select the file data (I put pData here as a placeholder, and assume it will be a byte[])
using (OleDbCommand cmd = new OleDbCommand("select pData from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.ContentType = "image/png";// put the content type here
context.Response.BinaryWrite((byte[])rdr[0]);
}
}
}
}
}
Note the using pattern which ensures proper resources cleanup once used. Also, ideally you could cache the data on the client using proper cache HTTP headers (like if-modified-since) but this is another story ...

How to create an image column in a SQL Server table and retrieve it in ASP.NET using VB

I want to know how to create an image column in a SQL Server table and retrieve it in ASP.NET using VB.NET
create table Tbl(ID int primary key,Name varchar(20),Image ....)
You want to use the VARBINARY(MAX) to store this data.
As to the code side, here is a good, brief answer.
From the answer:
FileStream st = new FileStream(#"C:\filename.jpg", FileMode.Open);
byte[] buffer = new byte[st.Length];
st.Read(buffer, 0, (int)st.Length);
st.Close();
SqlConnection conn = new SqlConnection("...");
SqlCommand cmd = new SqlCommand(
"UPDATE SomeTable SET image=#image WHERE ID = 1", conn);
cmd.Parameters.AddWithValue("#image", buffer);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
Save and Retrieve Files from SQL Server Database using ASP.Net
Storing and Retrieving Images/Files In Sql Server - VB.NET
in the sql server create the column with type: image.
and in the asp, use this example code: (it's in c#)
string con = "your connection string"
var Image = (from A in YourTblImage
select A).First();//to get one record of the table use the `first`
FileStream fs = new FileStream(#"yourPath to save the image", FileMode.Create);
try
{
System.Data.Linq.Binary img = image.imageColumnName;
byte[] imageK = img.ToArray();
fs.Write(imageK, 0, imageK.Length);
}
catch (Exception ex)
{
string str = ex.Message;
}
finally
{
fs.Close();
}

SQLiteException: Unable to open the database file

I'm new to windows mobile programming and I'm trying to create a Windows Mobile 6 application using sqlite. Write now I have built a dummy test application where I try to read the contents of a an sqlite table.
The problem is that I keep receiving SQLiteException: Unable to open the database file.
My code is below:
using (var cn = new SQLiteConnection(#"Data Source=C:myfirsttest.s3db;"))
{
try
{
//Connect to SQLite database
cn.Open();
//Create the SQL Command
var cmd = new SQLiteCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM MyTable";
//Retrieve the records using SQLiteDataReader
var dr = cmd.ExecuteReader();
while (dr.Read())
{
//display records
var id = dr["ID"].ToString();
}
}
catch(Exception ex)
{
//display any exeptions
var except = ex.Message;
}
finally
{
cn.Close();
}
}
Can anyone help me please with that? Or suggest a tutorial where I can find how to setup sqlite in a windows mobile 6 project?
Windows CE (the base OS for WinMo) does not have drives nor does it have a concept of a working folder. This means that all paths must be fully qualified. You probably want something like:
new SQLiteConnection(#"Data Source=\myfirsttest.s3db;")
or
new SQLiteConnection(#"Data Source=\[my app path]\myfirsttest.s3db;")

Resources