using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.IO;
namespace ImageToDatabase
{
class Program
{
static void Main(string[] args)
{
string server = ""; // Your server
string database = ""; // Your database;
string image_path = ""; // Path to image file.
string provider = "server=" + server + ";Database=" + database + ";Integrated Security=SSPI";
SqlConnection sqlcon = new SqlConnection(provider);
FileStream fs = File.OpenRead(image_path);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
try
{
sqlcon.Open();
Console.WriteLine(sqlcon.State.ToString());
/*
* Create a database with 2 fields.
* Field1: Name: image_id, DataType: int PRIMARY_KEY, IDENTITY = YES
* Field2: Name: image_data, DataType: VarBinary(MAX)
*
* Save Database table as tbl_image.
* */
// SQL required to store the image byte data int to the image_data field.
string sql ="INSERT INTO tbl_image (image_data) VALUES(@image_data)";
SqlCommand cmd = new SqlCommand(sql, sqlcon);
cmd.Parameters.Add("@image_data", System.Data.SqlDbType.Binary);
cmd.Parameters["@image_data"].Value = data;
cmd.ExecuteNonQuery();
}
catch (Exception er)
{
Console.WriteLine(er.Message);
}
Console.ReadKey();
}
}
}
Sunday, February 20, 2011
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment