class Program
{
static void Main(string[] args)
{
People p = new People();
Insert(p);
}
public static bool Insert(object obj)
{
Type type = obj.GetType();
string tableName = "tb_" + type.Name;
string sql = "insert into " + tableName + "(";
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo pInfo in properties)
{
sql += pInfo.Name + ",";
}
sql = sql.Substring(0, sql.LastIndexOf(','));
sql += ") values(";
foreach (PropertyInfo pInfo in properties)
{
sql += "'" + pInfo.GetValue(obj, null) + "',";
}
sql = sql.Substring(0, sql.LastIndexOf(','));
sql += ")";
return true;
}
}
class People
{
public string Name { set; get; }
public string Age { set; get; }
public string Sex { set; get; }
}
本文介绍了一个使用C#动态构建SQL插入语句的例子。该示例通过反射获取对象属性,并将其转换为SQL字段及值,实现了不同对象类型的通用插入操作。
687

被折叠的 条评论
为什么被折叠?



