C # access to one of the SQL Server databases: binary access picture files

Source: Internet
Author: User

Create a project

1. Add a table named rwtest to the SQL Server MYTest database. The table field is set as follows:

A. uniquely identifies the field name is "ID"and the type is Int.

B. a field of type VarChar called "Description" with a field length of

c. a field of type Image called "Imgfield" .

2. start visual Studio. NET and create a new Visual C # Window S Application project.

3. Drag two Button controls from the toolbar to the default form, Form1 .

4.        in the Properties window, modify name to buttonfiletodb , text properties are saved from file to database , then modify name to buttondbtofile , text The property is saved from the database to the file .

5 Place 2 TextBox and 1 PictureBox from the toolbar Controls:theName property is:textboxgetid, textboxgetdescription, picture Boxgetimage , showing IDs read from the database ,Description,Imgfield fields.

SOURCE Example

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

using System.IO;

using System.Collections;

// Database Description: MyTest database, rwtest Table , contains 3 columns: ID (int), Description (varchar), Imgfield (Image)

namespace rwimgsql

{

public partial class Form1 : Form

    {

public Form1 ()

        {

InitializeComponent ();

        }

private void Buttonfiletodb_click (object sender, EventArgs e)

        {

SqlConnection sqlconnection = new SqlConnection ("Data Source = Liuxueqin; Initial catalog=mytest;integrated security=true ");

SqlDataAdapter sqldataadapter = New SqlDataAdapter ( > "SELECT * from Rwtest", SqlConnection);

sqlcommandbuilder sqlcommandbuilder = new SqlCommandBuilder(SqlDataAdapter );

DataSet DataSet = new DataSet("rwtest");

sqldataadapter.missingschemaaction = MissingSchemaAction. AddWithKey; // Identify existing DataSet the action to perform if the schema does not match the incoming data.

String currentexename = system.diagnostics. Process. GetCurrentProcess (). Mainmodule.filename;

String imagefile = System.IO. Path. GetDirectoryName (currentexename) + "\f1.jpg";

System.IO. FileStream FileStream = new FileStream(imagefile, FileMode. OpenOrCreate, fileaccess. ReadWrite);

byte [] myData = new byte [filestream.length];

filestream.read (myData, 0, System. Convert. ToInt32 (filestream.length)); // reads a block of bytes from the stream and writes the data to the buffer

filestream.close ();

try

            {

Sqldataadapter.fill (DataSet, "Rwtest");

//datarow represents a row of data in a DataTable

System.Data. DataRow DataRow;

dataRow = dataset.tables["Rwtest"]. NewRow ();

datarow1["ID"] = 1;

datarow1["Description"] = "This would is Description text";

datarow1["Imgfield"] = MyData;

dataset.tables["Rwtest"]. Rows.Add (DataRow);

sqldataadapter.update (DataSet, "Rwtest");

sqlconnection.close ();

MessageBox. Show (" write to database success!") ", " Information tips , messageboxbuttons. OK, MessageBoxIcon. Information);

            }

Catch (Exception ex)

            {

If (sqlconnection.state = = ConnectionState. Open)

                {

sqlconnection.close ();

                }

MessageBox. Show ( Write database failed )+ex. Message, " informational hint ", messageboxbuttons. OK, MessageBoxIcon. ERROR);

            }

        }

private void Buttondbtofile_click (object sender, EventArgs E

        {

SqlConnection SqlConnection = new SqlConnection("Data Source=liuxueqin ; Initial catalog=mytest;integrated security=true ");

SqlDataAdapter SqlDataAdapter = new SqlDataAdapter("SELECT * From Rwtest ", SqlConnection);

sqlcommandbuilder sqlcommandbuilder = new SqlCommandBuilder(SqlDataAdapter );

DataSet DataSet = new DataSet("rwtest");

byte[] MyData = new byte[0];

Sqldataadapter.fill (DataSet, "Rwtest");

DataRow myrow;

myrow = dataset.tables["Rwtest"]. Rows[0];

MyData = (byte[]) myrow["Imgfield"];

int arraysize = mydata.getupperbound (0);

String currentexename = system.diagnostics. Process. GetCurrentProcess (). Mainmodule.filename;

string imagefile = System.IO. Path. GetDirectoryName (currentexename) + "\f2.jpg";

FileStream fs = new FileStream(imagefile, FileMode. OpenOrCreate, fileaccess. Write);

FS. Write (MyData, 0, arraysize);

FS. Close ();

//--- 2 textBox and 1 on the interface PictureBox that is used to display the data read from the database. ID , Description , ImageField Field

textboxgetid.text = myrow["ID"]. ToString ();

textboxgetdescription.text = myrow["Description"]. ToString ();

pictureboxgetimage.image = Image. FromFile (ImageFile);

if (sqlconnection.state = = connectionstate. Open)

            {

sqlconnection.close ();

            }

MessageBox. Show (" read data from database success!") ", " Information tips , messageboxbuttons. OK, MessageBoxIcon. Information);

        }

}

}

 





</

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.