一個(gè)C#向SQL Server數(shù)據(jù)庫保存圖片的代碼實(shí)例
作者:刁健
本文主要介紹了用C#將圖片保存到SQL Server數(shù)據(jù)庫中的過程,并給出了全部的代碼,希望能對(duì)讀者有所幫助。
我們?cè)谟?strong>C#和SQL Server數(shù)據(jù)庫開發(fā)應(yīng)用程序時(shí),常常會(huì)用到圖片處理的問題。那么C#是怎樣將圖片保存到SQL Server數(shù)據(jù)庫中的呢?本文我們通過一個(gè)實(shí)例代碼來介紹這一過程。
首先打開一個(gè)圖片文件代碼如下:
- private void Image(object sender, EventArgs e)
- {
- OpenFileDialog fileDialog = new OpenFileDialog();
- fileDialog.Filter = "圖片文件|*.jpg";
- fileDialog.Multiselect = false;
- if (fileDialog.ShowDialog() == DialogResult.OK)
- {
- //圖片地址
- this.textBoxImage.Text = fileDialog.FileName;
- }
- }
保存圖片:
- private void Save(object sender, EventArgs e)
- {
- //把圖片轉(zhuǎn)換為二進(jìn)制保存
- Stream stream = new FileStream(this.textBoxImage.Text.Trim(), FileMode.Open);
- byte[] data=new byte[stream.Length];
- stream.Read(data, 0, data.Length);
- stream.Close();
- //保存到數(shù)據(jù)庫
- string connectionString = 連接字符串;
- SqlConnection connection = new SqlConnection(connectionString);
- //sql語句
- string sql="@INSERT INTO 數(shù)據(jù)庫名稱 (Image) VALUES(@Image)";
- SqlCommand cmd = new SqlCommand(sql, connection);
- SqlParameter parameter=new SqlParameter ()
- {ParameterName="@Image",Value=data,SqlDbTypeSqlDbType=SqlDbType.Image};
- cmd.Parameters.AddRange(parameters);
- if (connection.State == ConnectionState.Closed)
- {
- connection.Open();
- }
- int count = cmd.ExecuteNonQuery();
- if (count > 0)
- {
- MessageBox.Show("success");
- }
- else
- {
- MessageBox.Show("failed");
- }
- connection.Close();
- }
- }
執(zhí)行完上述代碼,就可以成功地將圖片保存到SQL Server數(shù)據(jù)庫中了。
【編輯推薦】
責(zé)任編輯:趙鵬
來源:
博客園