更方便快捷的外部操作数据库的方法(另类玩法)
程序员文章站
2024-03-05 12:03:24
复制代码 代码如下: using system; using system.data; using system.data.sqlclient; public class...
复制代码 代码如下:
using system;
using system.data;
using system.data.sqlclient;
public class helper
{
public static void main()
{
//连接字符串
string strcon = "server = .;database = blog;uid = sa;pwd = 1";
sqlhelper helper = new sqlhelper(strcon);
//表employee中有neme(varchar(20)),age(int),sex(bit)三个字段;
string sql = "select * from employee";
sqldatareader reader = helper.reader(sql,null);
using (reader)
{
while (reader.read())
{
console.writeline(reader["name"].tostring());
}
}
/*string sql = "insert into employee values(@name,@age,@sex)";
sqlparameter[] ps = new sqlparameter[]
{
new sqlparameter("@name",sqldbtype.varchar,20),
new sqlparameter("@age",sqldbtype.int),
new sqlparameter("@sex",sqldbtype.int)
};
ps[0].value = "张宇";
ps[1].value = 40;
ps[2].value = 1;
helper.executenonquery(sql,ps);*/
}
}
public class sqlhelper
{
private sqlconnection con = null;
private sqlcommand cmd = null;
public sqlhelper (string strcon)
{
con = new sqlconnection(strcon);
cmd = new sqlcommand();
cmd.connection = con;
}
//执行初始化command对象
private void preparedcommand(string sql,params sqlparameter[]param)
{
cmd.commandtext = sql;
//清空parameteras中的对象
cmd.parameters.clear();
if (param!=null)
{
foreach (sqlparameter p in param)
{
cmd.parameters.add(p);
}
}
con.open();
}
/*执行非查询语句*/
//有参数
public int executenonquery(string sql,params sqlparameter[] param)
{
preparedcommand(sql,param);
int i = cmd.executenonquery();
close();
return i;
}
//无参数
public int executenonquery(string sql)
{
preparedcommand(sql,null);
int i = cmd.executenonquery();
close();
return i;
}
/*执行查询语句*/
//有参数
public sqldatareader reader(string sql,params sqlparameter[] param)
{
preparedcommand(sql,param);
return cmd.executereader();
}
//无参数
public sqldatareader reader(string sql)
{
preparedcommand(sql,null);
return cmd.executereader();
}
public void open()
{
con.open();
}
public void close()
{
cmd.dispose();
con.close();
}
}
上一篇: 浅谈Java编程中的单例设计模式
下一篇: php 魔术常量详解及实例代码