参数化的应用

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

namespace sql_str {
public class sql_str {
public DataSet myds(SqlCommand return_com) {
sql_db.db db_str
= new sql_db.db();
SqlConnection mycon
= new SqlConnection(db_str.db_str());
SqlDataAdapter da
= new SqlDataAdapter(return_com);
return_com.Connection
= mycon;
mycon.Open();
DataSet ds
= new DataSet();
da.Fill(ds);
return ds;
}
public DataSet methods_ds(string methods_name, List<user> my_user) {
SqlCommand mycom
= new SqlCommand();
switch (methods_name) {
case "1":
mycom.CommandText
= "select f_id from t_htmltable where f_id = @id";
break;
case "2":
mycom.CommandText
= "select f_name from t_htmltable where f_name = @name";
break;
case "3":
mycom.CommandText
= "select f_text from t_htmltable where f_text = @text";
break;
case "4":
mycom.CommandText
= "select * from t_htmltable where f_text = @text and f_id = @id";
break;
}
SqlParameter mypara_id
= new SqlParameter("@id", SqlDbType.Int);
SqlParameter mypara_name
= new SqlParameter("@name", SqlDbType.VarChar);
SqlParameter mypara_text
= new SqlParameter("@text", SqlDbType.VarChar);
foreach (var i in my_user) {
if (i.Id != 0) {
mypara_id.Value
= i.Id;
}
else {
mypara_id.Value
= 0;
}
if (i.Name != "") {
mypara_name.Value
= i.Name;
}
else {
mypara_name.Value
= "";
}
if (i.Text != "") {
mypara_text.Value
= i.Text;
}
else {
mypara_text.Value
= "";
}
}
mycom.Parameters.Add(mypara_id);
mycom.Parameters.Add(mypara_name);
mycom.Parameters.Add(mypara_text);
return myds(mycom);
}
public DataSet return_ds(List<user> my_user, string methods_id) {
return methods_ds(methods_id, my_user);
}
}
public class user {
int id = 0;
string name = "";
string text = "";
public int Id {
set { this.id = value; }
get { return this.id; }
}
public string Name {
set { this.name = value; }
get { return this.name; }
}
public string Text {
set { this.text = value; }
get { return this.text; }
}
public user() {

}
public user(string variable_name, int variable_value) {
switch (variable_name) {
case "f_id":
this.id = variable_value;
break;
}
}
public user(string variable_name, string variable_value) {
switch (variable_name) {
case "f_name":
this.name = variable_value;
break;
case "f_text":
this.text = variable_value;
break;
}
}
}
}
调用部分 sql_str.sql_str mysql_str = new sql_str.sql_str();
List
<sql_str.user> list = new List<sql_str.user>();
list.Add(
new sql_str.user("f_text", "123123"));
list.Add(
new sql_str.user("f_name", "alex"));
list.Add(
new sql_str.user("f_id", 1));
Gridview1.DataSource
= mysql_str.return_ds(list,"4");
Gridview1.DataBind();

posted on 2011-02-15 21:22  卑鄙De小贝  阅读(424)  评论(4)    收藏  举报

导航