Wednesday, June 18, 2008

SqlDataadapter

//*** don't run more than once ***
String selectCommand = "SELECT EmployeeID FROM Employees";
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["Sql_ConnectString"]);
SqlDataAdapter da = new SqlDataAdapter(selectCommand, conn);

DataTable table = new DataTable("Employees");
da.FillSchema(table, SchemaType.Source);
da.Fill(table);

conn.Open();
foreach(DataRow row in table.Rows)
{
Int32 employeeId = (Int32)row["EmployeeID"];

String sqlRead = "SELECT Photo FROM Employees WHERE EmployeeID=" + employeeId;
SqlCommand cmdRead = new SqlCommand(sqlRead, conn);

MemoryStream ms = new MemoryStream();
Byte[] image = (Byte[])cmdRead.ExecuteScalar();
ms.Write(image, MSACCESSIMAGEOFFSET, image.Length - MSACCESSIMAGEOFFSET);

String sqlWrite = "UPDATE Employees SET Photo = @Photo WHERE EmployeeID=" + employeeId;
SqlCommand cmdWrite = new SqlCommand(sqlWrite, conn);

//Create parameter for insert command and add to SqlCommand object.
SqlParameter prm = new SqlParameter("@Photo", SqlDbType.VarBinary, ms.ToArray().Length, ParameterDirection.Input, false,
0, 0, null, DataRowVersion.Current, ms.ToArray());
cmdWrite.Parameters.Add(prm);

//Execute query.
cmdWrite.ExecuteNonQuery();
}
conn.Close();
}
}

No comments: