C#與sql進行圖片存取
阿新 • • 發佈:2020-10-10
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 using System.IO; 12 using System.Data.SqlClient; 13 1415 16 namespace 圖片存取 17 { 18 public partial class 例項 : Form 19 { 20 public 例項() 21 { 22 InitializeComponent(); 23 } 24 public static string str = "server=192.168.0.102;database=mysql;uid=sa;pwd=a123456"; 25 private void 例項_Load(object sender, EventArgs e)26 { 27 28 } 29 30 /// <summary> 31 /// 32 /// </summary> 33 /// <param name="path"></param> 34 public static void InsertImg(string path) 35 { 36 37 byte[] bytes = File.ReadAllBytes(path); 38 SqlConnection con = newSqlConnection(str); 39 con.Open(); 40 SqlCommand cmd = new SqlCommand("insert into table_2 values(@image)",con); 41 cmd.Parameters.Add("@image", SqlDbType.Image).Value = bytes; 42 cmd.ExecuteNonQuery(); 43 con.Close(); 44 45 //cmd.Dispose(); 46 47 } 48 49 public static void ReadImg(string path) 50 { 51 SqlConnection con = new SqlConnection(str); 52 con.Open(); 53 SqlCommand cmd = new SqlCommand("select image from table_2 ",con); 54 object scalar = cmd.ExecuteScalar(); 55 byte[] bytes = (byte[])scalar; 56 57 File.WriteAllBytes(path, bytes); 58 con.Close(); 59 //cmd.Dispose(); 60 61 } 62 63 private void button1_Click(object sender, EventArgs e) 64 { 65 InsertImg(@"C: \Users\Administrator\Desktop\0811\3-2.jpg"); 66 ReadImg(@"C: \Users\Administrator\Desktop\0811\3-2-1.jpg"); 67 } 68 } 69 }