WinForm連接數據庫增刪改查


對象屬性

using System;
using System.Collections.Generic;
using System.Text;

namespace LeikuObject
{
    public class TelObject
    {
        private int _Code;

        public int Code
        {
            get { return _Code; }
            set { _Code = value; }
        }
        private string _Name;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        private string _Sex;

        public string Sex
        {
            get { return _Sex; }
            set { _Sex = value; }
        }
        private string _Phone;

        public string Phone
        {
            get { return _Phone; }
            set { _Phone = value; }
        }
    }
}

函數

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using LeikuObject;

namespace LeikuFunction
{
    public class Function
    {
        SqlConnection conn;
        SqlCommand cmd;
        string sr = "server=.;database=lianxi;uid=sa;pwd=123";
        public Function()
        {
            conn = new SqlConnection(sr);//通過構造函數連接數據庫
            cmd = conn.CreateCommand();//創建一個與SqlConnection(表示一個連接數據庫的鏈接)和SqlCommand(表示要對數據庫進行操作的SQL語句)相關聯的的對象
        }

        /// <summary>
        /// 查詢
        /// </summary>
        /// <returns></returns>
        public List<TelObject> select()
        {
            List<TelObject> list = null;
            cmd.CommandText = "select * from tel";//存儲SQL語句
            conn.Open();//打開數據庫連接
            SqlDataReader dr = cmd.ExecuteReader();//SqlDataReader 提供一種從數據庫讀取行的只進流方式 ExecuteReader:將 CommandText 發送到 Connection 並生成一個 SqlDataReader
            
            if (dr.HasRows)//判斷dr中有沒有數據
            {
                list = new List<TelObject>();              
                while (dr.Read())//dr中讀取到的行 返回true 讀取的行會先存在dr中 
                {
                    TelObject t = new TelObject();//這句如果放在while外面,就會只造了一個TelObject對象 只會帶着一個對象的值存入list集合中
                    t.Code=int.Parse(dr["code"].ToString());
                    t.Name = dr["name"].ToString();
                    t.Sex = dr["sex"].ToString();
                    t.Phone = dr["iph"].ToString();
                    list.Add(t);
                }
            }
            cmd.Dispose();//銷毀cmd
            conn.Close();//關閉數據庫連接
            return list;
        }

        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="code"></param>
        public void delete(int code)
        {
            cmd.CommandText = "delete from tel where code=@code";//使用@占位符 可以避免注入攻擊
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@code",code);//給占位符賦值
            conn.Open();
            cmd.ExecuteNonQuery();//執行SQL語句,並返回受影響的行
            cmd.Dispose();
            conn.Close();
        }

        /// <summary>
        /// 單獨查詢
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public TelObject select(int code)
        {
            TelObject t = null;
            cmd.CommandText = "select *from tel where code=@code";
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@code", code);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                t = new TelObject();
                if (dr.Read())//如果不加這一步,直接賦值,會報錯?
                {
                    t.Code = int.Parse(dr["code"].ToString());
                    t.Name = dr["name"].ToString();
                    t.Sex = dr["sex"].ToString();
                    t.Phone = dr["iph"].ToString();
                }
            } 
            cmd.Dispose();
            conn.Close();
            return t;
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="t"></param>
        public void insert(TelObject t)
        {
            cmd.CommandText = "insert into tel values(@code,@name,@sex,@iph)";
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@code", t.Code);
            cmd.Parameters.Add("@name", t.Name);
            cmd.Parameters.Add("@sex", t.Sex);
            cmd.Parameters.Add("@iph", t.Phone);
            conn.Open();
            cmd.ExecuteNonQuery();//執行SQL語句,並返回受影響的行
            cmd.Dispose();
            conn.Close();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t"></param>
        public void update(TelObject t)
        {
            cmd.CommandText = "update tel set name=@name,sex=@sex,iph=@iph where code=@code";
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@code", t.Code);
            cmd.Parameters.Add("@name", t.Name);
            cmd.Parameters.Add("@sex", t.Sex);
            cmd.Parameters.Add("@iph", t.Phone);
            conn.Open();
            cmd.ExecuteNonQuery();//執行SQL語句,並返回受影響的行
            cmd.Dispose();
            conn.Close();
        }

        /// <summary>
        /// 模糊查詢
        /// </summary>
        /// <param name="name"></param>
        /// <param name="sex"></param>
        /// <returns></returns>
        public List<TelObject> select(string name,string sex)
        {
            List<TelObject> list = null;
            cmd.CommandText = "select * from tel where name like '%"+name+"%' and sex like '%"+sex+"%'";
            //這個地方不能用占位符,不解,暫時用拼接字符串吧         
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();//SqlDataReader 提供一種從數據庫讀取行的只進流方式 ExecuteReader:將 CommandText 發送到 Connection 並生成一個 SqlDataReader

            if (dr.HasRows)//判斷dr中有沒有數據
            {
                list = new List<TelObject>();
                while (dr.Read())//dr中讀取到的行 返回true 讀取的行會先存在dr中 
                {
                    TelObject t = new TelObject();//這句如果放在while外面,就會只造了一個TelObject對象 只會帶着一個對象的值存入list集合中
                    t.Code = int.Parse(dr["code"].ToString());
                    t.Name = dr["name"].ToString();
                    t.Sex = dr["sex"].ToString();
                    t.Phone = dr["iph"].ToString();
                    list.Add(t);
                }
            }
            cmd.Dispose();//銷毀cmd
            conn.Close();//關閉數據庫連接
            return list;
        }
    }
}

From1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LeikuObject;
using LeikuFunction;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form//主窗體
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static int time = 0;//定義靜態成員
        public void chushiselect(List<TelObject> list)//顯示查詢結果的函數
        {
            listView1.Columns.Clear();//清空列名,為了防止連續重復調用函數,重復插入列名
            listView1.Columns.Add("編號");//添加列名,第一列索引是0 Columns[0] 第二項Columns[1]
            listView1.Columns.Add("姓名");
            listView1.Columns.Add("性別");
            listView1.Columns.Add("電話");
            listView1.Items.Clear();//清空行,為了防止連續重復調用函數,重復插入行
            //TelObject t = new TelObject();
            if (list!=null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    listView1.Items.Add(list[i].Code.ToString());//添加行,行的第一列數據
                    //第一行添加第一列數據時不能這么寫listView1.Items[i].SubItems.Add(list[i].Code.ToString())
                    //添加之前第一列是空的 Items[i].SubItems 空集合里索引0里的SubItems報錯 因為index為null
                    listView1.Items[i].SubItems.Add(list[i].Name);//這一行的,第二列數據,也就是Items這個集合里索引是0的數據
                    listView1.Items[i].SubItems.Add(list[i].Sex);
                    listView1.Items[i].SubItems.Add(list[i].Phone);
                }
            }
        }
        private void btselect_Click(object sender, EventArgs e)//查詢按鈕
        {
            time = 1;
        }

        private void btdelete_Click(object sender, EventArgs e)//刪除按鈕
        {
            //MessageBox.Show(listView1.Items[0].SubItems[1].Text); 可以獲取到這一行的第二列數據
            //MessageBox.Show(listView1.SelectedItems[0].SubItems[1].Text); 可以獲取到選中行的第二列數據
            if (listView1.SelectedItems.Count>0)//判讀是否選中了一行
            {
                int code = int.Parse(listView1.SelectedItems[0].Text);//獲取選中行的第一列數據 也可以寫成listView1.SelectedItems[0].SubItems[0].Text
                new Function().delete(code);
                time = 1;
            }
            
        }

        private void btinsert_Click(object sender, EventArgs e)//增加按鈕
        {
            Form2 f = new Form2();
            f.Show();
        }

        private void timer1_Tick(object sender, EventArgs e)//時鍾組件,一直在后台等待,當time值有變化,就執行操作
        {
            if (time==0)
            {
                
            }
            else if (time==1)
            {
                List<TelObject> list = new Function().select();
                chushiselect(list);
            }
            time = 0;
        }

        private void btupdate_Click(object sender, EventArgs e)//修改按鈕
        {
            if (listView1.SelectedItems.Count > 0)
            {
                int code = int.Parse(listView1.SelectedItems[0].Text);
                Form3 f = new Form3(code);//通過構造函數傳值,把code傳給Form3
                f.Show(); 
            } 
        }

        private void btpreselect_Click(object sender, EventArgs e)//條件按鈕
        {
            if (txtmainname.Text.Length>0||txtmainsex.Text.Length>0)
            {
                string name = txtmainname.Text;
                string sex = txtmainsex.Text;
                List<TelObject> list = new Function().select(name, sex);
                chushiselect(list);
            }
        }
    }
}

Form2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LeikuFunction;
using LeikuObject;

namespace WindowsFormsApplication3
{
    public partial class Form2 : Form//增加對話框
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void btzengjia_Click(object sender, EventArgs e)
        {
            //判讀文本框里是不是有內容
            if (txtcode.Text.Length>0&&txtname.Text.Length>0&&txtsex.Text.Length>0&&txtphone.Text.Length>0)
            {
                TelObject t = new TelObject();
                t.Code = int.Parse(txtcode.Text);
                t.Name = txtname.Text;
                t.Sex = txtsex.Text;
                t.Phone = txtphone.Text;
                new Function().insert(t);
                Close();//增加完信息關閉增加對話框
                Form1.time = 1;//調用Form1中的靜態成員,修改time值,為了重新查詢數據庫,把增加的信息顯示出來
            }
            else
            {
                MessageBox.Show("信息有誤");
            }
        }
    }
}

Form3

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LeikuObject;
using LeikuFunction;

namespace WindowsFormsApplication3
{
    public partial class Form3 : Form
    {
        private int Code;
        public Form3(int code)
        {
            InitializeComponent();
            Code = code;
        }

        private void btxiugai_Click(object sender, EventArgs e)//修改按鈕
        {
            //判讀修改后的文本中是否有內容
            if (txtxname.Text.Length>0&&txtxsex.Text.Length>0&&txtxphone.Text.Length>0)
            {
                TelObject t = new TelObject();
                t.Code = int.Parse(txtxcode.Text);
                t.Name = txtxname.Text;
                t.Sex = txtxsex.Text;
                t.Phone = txtxphone.Text;
                new Function().update(t);
                Close();
                Form1.time = 1;
            }
        }

        private void Form3_Load(object sender, EventArgs e)//Form3窗體打開時就會顯示的值
        {
            TelObject t = new Function().select(Code);
            txtxcode.Text = t.Code.ToString();
            txtxname.Text = t.Name;
            txtxsex.Text = t.Sex;
            txtxphone.Text = t.Phone;
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM