今天我們來學習學習通過反射技術來生成sql語句。
反射提供了封裝程式集、模組和型別的物件。您可以使用反射動態地建立型別的例項,將型別繫結到現有物件,或從現有物件中獲取型別。然後,可以呼叫型別的方法或訪問其字段和屬性。
1.先建立實體類
使用者實體類:
public class user書籍實體類:public string username
public string password
public int age
public string phonenumber
public string address
}
public class book2.通過反射技術來生成insert語句(舉個例子而已,只生成insert語句)public string bookname
public string isbn
public string author
public double price
}
/// /// 泛型方法,反射生成sqlinsert語句3.測試///
/// 實體型別
/// 實體物件
///
public string createinsertsql(t entity)
//**去掉最後乙個逗號
sb.remove(sb.length - 1, 1);
//5.再次遍歷,形成引數列表"(@xx,@xx@xx)"的形式
foreach (propertyinfo prop in props)
//**去掉最後乙個逗號
sb.remove(sb.length - 1, 1);
return sb.tostring();
}
class program結果:}

但是,我們發現id是主鍵,假設id是自增長的,我們生成的sql(insert)語句中就不應該有id,在這裡我用自定義attribute的方法來解決這個問題。
4.先新建乙個類,繼承attribute類
public class keyattribute : attribute這個類僅此而已就夠了。
5.在實體類中的id這個欄位上加上[key]標記
public class bookpublic string bookname
public string isbn
public string author
public double price
}
public class user6.加好標記之後,我們只需要這createinsertsql(t entity)這個方法中的兩個foreach迴圈體中加一些判斷即可public string username
public string password
public int age
public string phonenumber
public string address
}
foreach (propertyinfo prop in props)//將屬性的名字加入到字串中
}
foreach (propertyinfo prop in props)7.測試}
使用反射實現生成新增 修改sql語句
1.生成新增sql語句 單獨乙個model時 public static string insertsql t t object value pi.getvalue t,null if value null continue 未給值,null value commonfunc.uninjection...
sql語句生成sql指令碼
sql語句有一種特別的用法,相信很多人還不知道,我也是後來學到的,因此拿來跟大家分享下 生成sql指令碼 舉個例子 select 1 from student 如果表中有資料的話,你就會發現查詢的結果會是 根據這個原理,我們可以用來生成sql指令碼,以下就是例項 例項1 乙個簡單的例子 select...
動態生成SQL語句
procedure tform1.excutebtnclick sender tobject begin sqlquery1.sql.clear sqlquery1.sql.add select item.text from table.text item.text為輸入查詢專案編輯框,table....