图像保存在SQL? [英] image saving in sql?

查看:48
本文介绍了图像保存在SQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,hi试图将图像保存到sqlserver并将其显示到网格中..但是在运行时此代码中出现了erorr并记录未保存到数据库吗?

//读取图像文件

byte[] ReadFile(string sPath)
        {

            byte[] data = null;
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fStream);
            data = br.ReadBytes((int)numBytes);
            return data;
        }
//display image in picture box when i select perticular cell
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["cdCustomerPhoto"].Value;
                Image newImage;
                using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
                {
                    ms.Write(imageData, 0, imageData.Length);
                    newImage = Image.FromStream(ms, true);
                }

                pictureBox1.Image = newImage;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }



//btnsave clikc

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] imageData = ReadFile(txtImagePath.Text);
                //string ID = textBox1.Text;
                string Name = tbName.Text;
                string Mobile = tbMobile.Text;
                string Age = tbAge.Text;
                string JoindDate = tbJoinDate.Text;
                string Sex = tbSex.Text;
                string DOB = tbDateOfBirth.Text;
                string IDProof = tbIDProof.Text;

                SqlConnection CN = new SqlConnection(@"Data Source=ythisbug;Initial Catalog=Exchange;Integrated Security=True;");
                string qry = "insert into tblCustomerDetails (cdCustomerName,cdCustomerSex,cdCustomerPhNo,cdCustomerDOB,cdCustomerJoinDate,cdCustomerAge,cdCustomerIDProofNo,cdCustomerPhoto) values(@Name,@Sex,@Mobile,@Dob,@Join,@Age,@Idproof,@ImageData)";

                SqlCommand SqlCom = new SqlCommand(qry, CN);
                //CN.Open();
               // SqlCom.Parameters.Add(new SqlParameter("@ID", (object)textBox1.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Name", (object)tbName.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Sex", (object)tbSex.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Mobile", (object)tbMobile.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Dob", (object)tbDateOfBirth.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Join", (object)tbJoinDate.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Age", (object)tbAge.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Idproof", (object)tbIDProof.Text));
                SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));
                CN.Open();
                SqlCom.ExecuteNonQuery();
                CN.Close();

                GetImagesFromDatabase();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
               

        }





//此错误在btn中单击save

at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at Exchange.CustomerRegistration.button1_Click(Object sender, EventArgs e) in C:\Users\ythisbug\Documents\Visual Studio 2008\Projects\ShiroorExchangeWindowsApp\Exchange\CustomerRegistration.cs:line 75




//

这是我的代码

  void  GetImagesFromDatabase()
      {
          尝试
          {
              SqlConnection CN =  SqlConnection( @" );
              SqlDataAdapter ADAP = 新建 SqlDataAdapter(" ,CN);
              DataSet DS =  DataSet();
              ADAP.Fill(DS," ); // 此行错误
              dataGridView1.DataSource = DS.Tables [" ];
          }
          捕获(例外)
          {
              MessageBox.Show(ex.ToString());
          }
      }


错误:

系统无效操作异常实例失败

在System.data.Common.dbdataadapter.fill(数据集数据集,字符串src表)
在c:\ Users \ ythisbug \ documents \ visual studio 2008 \ projects \ exchange \ exchange \ CustomerRegistration.cs:line 95中的Exchange.customerregistration.getImagesFromDatabase()中
谁能帮我解决这个问题.. 
在此先感谢

解决方案

只需使用以下内容:

 ADAP.Fill(DS);
dataGridView1.DataSource = DS.Tables [ 0 ]; 


好,根据添加的新错误,它似乎存在一些连接问题.确保您的连接字符串正确,并且能够连接到数据库.

您的问题是与数据库的连接.适配器在Fill期间内部处理连接,因此两个问题都仅指向一个连接问题.


更新:

我尝试了三个以上的示例项目来将图像保存在数据库中..bt无法正常工作.或者只是给我链接简单易行
使用Streded Procedures和C#.net从SQL Server存储和检索图像 [ ^ ]
C#相册查看器 [使用C#在SQL Server数据库中存储或保存图像 [^ ]
使用C#从SQL Server数据库中插入和检索图像 [ ^ ]


hi in my project am trying to save image into sqlserver and display it into grid..but while runtime am getting erorr in this code and record not saving to database?


//read image file

byte[] ReadFile(string sPath)
        {

            byte[] data = null;
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fStream);
            data = br.ReadBytes((int)numBytes);
            return data;
        }
//display image in picture box when i select perticular cell
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["cdCustomerPhoto"].Value;
                Image newImage;
                using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
                {
                    ms.Write(imageData, 0, imageData.Length);
                    newImage = Image.FromStream(ms, true);
                }

                pictureBox1.Image = newImage;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }



//btnsave clikc

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] imageData = ReadFile(txtImagePath.Text);
                //string ID = textBox1.Text;
                string Name = tbName.Text;
                string Mobile = tbMobile.Text;
                string Age = tbAge.Text;
                string JoindDate = tbJoinDate.Text;
                string Sex = tbSex.Text;
                string DOB = tbDateOfBirth.Text;
                string IDProof = tbIDProof.Text;

                SqlConnection CN = new SqlConnection(@"Data Source=ythisbug;Initial Catalog=Exchange;Integrated Security=True;");
                string qry = "insert into tblCustomerDetails (cdCustomerName,cdCustomerSex,cdCustomerPhNo,cdCustomerDOB,cdCustomerJoinDate,cdCustomerAge,cdCustomerIDProofNo,cdCustomerPhoto) values(@Name,@Sex,@Mobile,@Dob,@Join,@Age,@Idproof,@ImageData)";

                SqlCommand SqlCom = new SqlCommand(qry, CN);
                //CN.Open();
               // SqlCom.Parameters.Add(new SqlParameter("@ID", (object)textBox1.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Name", (object)tbName.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Sex", (object)tbSex.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Mobile", (object)tbMobile.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Dob", (object)tbDateOfBirth.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Join", (object)tbJoinDate.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Age", (object)tbAge.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Idproof", (object)tbIDProof.Text));
                SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));
                CN.Open();
                SqlCom.ExecuteNonQuery();
                CN.Close();

                GetImagesFromDatabase();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
               

        }





//this errorr in btn click save

at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at Exchange.CustomerRegistration.button1_Click(Object sender, EventArgs e) in C:\Users\ythisbug\Documents\Visual Studio 2008\Projects\ShiroorExchangeWindowsApp\Exchange\CustomerRegistration.cs:line 75




//

here is my code

void GetImagesFromDatabase()
      {
          try
          {
              SqlConnection CN = new SqlConnection(@"Data Source=ythisBut;Initial Catalog=Exchange;Integrated Security=True;");
              SqlDataAdapter ADAP = new SqlDataAdapter("Select * from tblCustomerDetails", CN);
              DataSet DS = new DataSet();
              ADAP.Fill(DS, "tblCustomerDetails");//this line error
              dataGridView1.DataSource = DS.Tables["tblCustomerDetails"];
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.ToString());
          }
      }


error:

System invalid operation exception instance failure

at System.data.Common.dbdataadapter.fill(dataset dataset,string src table)
at Exchange.customerregistration.getImagesFromDatabase() in c:\Users\ythisbug\documents\visual studio 2008\projects\exchange\exchange\CustomerRegistration.cs:line 95


can any one help me to solve this..
thanks in advance

解决方案

Just use the following :

ADAP.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];


Ok, based on the new errors added, it looks like there is some connectivity issue. Make sure your connection string is correct and you are able to connect to DB.

Your issue is with connection to DB. Adapter internally deals with connection during Fill so both the issues point to one connectivity issue only.


UPDATE:

i tried more than three sample project for saving image in database..bt its not working.or just give me link simple and easy
Storing and Retrieving Images from SQL Server Using Strored Procedures and C#.net[^]
C# Photo Album Viewer[^]
Store or save images in SQL Server database using C# [^]
Inserting and Retrieving images from SQL Server Database using C#[^]


这篇关于图像保存在SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆