C# 自製連線dll

在使用過Entity Framework 後
用的速度很明顯感覺較慢
另外的做法是可以自製一個DLL
納入主程式作參考,這樣一來需要什麼方法
就直接呼叫該參考即可
好處是比較快,而且還可以客製化

自製dll程式碼:(注意:要建置)



public class NWDB
{
    SqlConnection conn;
    public NWDB()
    {
        conn = new SqlConnection(@"server=localhost;database=中文北風;UID=SQLUser;PWD=1234");
    }
        
    public NWDB(string Account, string Password)
    {
        SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
        scsb.DataSource = "localhost";
        scsb.InitialCatalog = "中文北風";
        scsb.UserID = Account;
        scsb.Password = Password;
        scsb.IntegratedSecurity = false;
        conn = new SqlConnection(scsb.ConnectionString);
    }

    public DataTable Customers()
    {
        SqlCommand cmd = new SqlCommand("SELECT 客戶編號,公司名稱,連絡人,連絡人職稱,地址 FROM 客戶", conn);
        conn.Open();
        SqlDataReader mydr = cmd.ExecuteReader();
        DataTable tt =new DataTable();
        tt.Load(mydr);
        mydr.Close();
        cmd.Dispose();
        conn.Close();
        return tt;
    }

    public bool CustomerInsert(string Id,string Name,string Contact,string ContactJob,string Address)
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO 客戶(客戶編號,公司名稱,連絡人,連絡人職稱,地址) VALUES(@Id,@Name,@Contact,@ContactJob,@Address)", conn);
        cmd.Parameters.Add("@Id", SqlDbType.NVarChar).Value = Id;
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = Name;
        cmd.Parameters.Add("@Contact", SqlDbType.NVarChar).Value = Contact;
        cmd.Parameters.Add("@ContactJob", SqlDbType.NVarChar).Value = ContactJob;
        cmd.Parameters.Add("@Address", SqlDbType.NVarChar).Value = Address;
        conn.Open();
        int i = cmd.ExecuteNonQuery();
        cmd.Dispose();
        conn.Close();
        if (i > 0)
            return true;
        else
            return false;
    }

}

在主程式中呼叫:(注意:要納入參考)


private void button6_Click(object sender, EventArgs e)
{
    NWDB.NWDB mydb = new NWDB.NWDB();
    dataGridView1.DataSource = mydb.Customers();
}

private void button7_Click(object sender, EventArgs e)
{
    NWDB.NWDB mydb = new NWDB.NWDB("SQLAdmin", "1234");
    bool ans = mydb.CustomerInsert("ZZZZZ", "賺錢好難公司", "王小明", "總裁", "桃園市龜龜路100號");
    if (ans)
        MessageBox.Show("新增成功");
    else
        MessageBox.Show("新增失敗");
}

留言

熱門文章