c#连接mdf文件示例分享
c#连接本地.mdf文件:项目中右键点击,新增——数据——基于服务的数据库,项目下直接生成.mdf数据库文件,后台(数据库的写入用参数传递):
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.data.sqlclient;
namespace ado.net
{
class program
{
static void main(string[] args)
{
//sqlserver 附加mdf文件
string datadir = appdomain.currentdomain.basedirectory;
if (datadir.endswith(@"\bin\debug\") || datadir.endswith(@"\bin\release\"))
{
datadir = system.io.directory.getparent(datadir).parent.parent.fullname;
appdomain.currentdomain.setdata("datadirectory", datadir);
}
using (sqlconnection conn = new sqlconnection(@"data source=.\sqlexpress;attachdbfilename=|datadirectory|\database1.mdf;integrated security=true;user instance=true"))
{
conn.open();
//写入一条数据
string strusername = "作业本";
string strpwd = "ab123456";
using (sqlcommand sqlcmd = conn.createcommand())
{
sqlcmd.commandtext = "insert into mytable1(name,password) values (@username,@pwd) ";//连接字符串进行参数化
sqlparameter[] sqlpara = new sqlparameter[] {
new sqlparameter("username",strusername),
new sqlparameter("pwd",strpwd)
};
sqlcmd.parameters.addrange(sqlpara); //把paramerter 数组参数添加到sqlcmd中
sqlcmd.executenonquery();
console.writeline("insert ok");
}
//从表中读取数据
string strread = "select id, name, password from mytable1 ";
using (sqlcommand sqlcmd = new sqlcommand(strread, conn))
{
//sqldatareader 逐行读取数据
using (sqldatareader sdr = sqlcmd.executereader())
{
while (sdr.read())
{
int id = sdr.getint32(sdr.getordinal("id")); //sdr.getordinal 获取列的序号
string name = sdr.getstring(sdr.getordinal("name"));
bool pwd = sdr.isdbnull(sdr.getordinal("password"));
console.writeline("id:{0},name:{1},pwd:{2}", id, name, pwd);
console.writeline(sdr.getstring(1));
}
}
}
conn.close();//此处可以省略,dispose()方法会自动检查
}
}
}
}
下一篇: Django内容增加富文本功能的实例