There are a number of different plugins and tools which can export image data in hex format from an MS SQL server to an actual file on the harddrive. If you have Visual Studio installed, however, the easiest way is to just write a small console program to select the data from the image column and save it to a file. For example:
static void Main(string[] args)
{
try
{
SqlConnection thisConnection = new SqlConnection(@"Server=192.168.1.1,1433;database=MyDb;User id=sa;Password=JdjdUD78!;");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT ImageData FROM [MyDatabase].[dbo].[Images] where ID = 1";
byte[] imgBytes = (byte[]) thisCommand.ExecuteScalar();
FileStream fs = new FileStream(@"C:\temp\image.jpg", FileMode.CreateNew, FileAccess.Write);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();
thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
Tag Archives: MSSQL
Basic SQL Server Query in C#
If you need to access a database on an MSSQL server programmatically (in C#) just to do some quick and dirty data extraction and perhaps manipulation, the following code snippet will get you started. Replace the connection string, table and columns names with whatever is appropriate for your task.
static void Main(string[] args)
{
try
{
SqlConnection thisConnection = new SqlConnection(@"Server=192.168.1.1,1433;database=NorthWind;User id=sa;Password=HIUHFuhf8;");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT [ID], [Name] FROM Customers";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
Console.WriteLine("\t{0}\t{1}", thisReader["ID"], thisReader["Name"]);
}
thisReader.Close();
thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}