天天看点

调用数据连接两种方法

1.web.config (配置文件) 中

<appsettings>

<add key="connectionstring" value="serverlocalhost\sqlexpress;uid=sa;pwd=123456;database=news"/>

</appsettings>

调用的时候

string strconn = system.configuration.configurationmanager.appsettings["connectionstring"].tostring();

sqlconnection conn = new sqlconnection(strconn);

2.或者不用web.config直接在文件中写

sqlconnection conn = new sqlconnection("server=.\\sqlexpress;uid=sa;pwd=123456;database=login");

如何是express版的数据库,一定要在服务器名的后面加上[url=file://%20%20ssqlexpress/]\\ssqlexpress[/url]

一个完整的例子

  string username = request.form["username"];

         string userpwd = request.form["userpwd"];

         sqlconnection con = new sqlconnection("server=localhost\\sqlexpress;uid=sa;pwd=123456;database=login");

         con.open();

         sqlcommand cmd=new sqlcommand("select count(*) from login where username='"+username+"' and userpwd='"+userpwd+"'",con);

         int count=convert.toint32(cmd.executescalar());

         if(count>0)

         {

         response.redirect("main.aspx");

         }

继续阅读