欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET中操作SQL数据库

程序员文章站 2023-10-22 09:43:56
在webconfig中配置连接字符串,代码如下:        

在webconfig中配置连接字符串,代码如下:

<connectionstrings>
        <add name="connectionstring" connectionstring="user id=用户名;password=密码;initial catalog=数据库名称;data source=服务器名称"/>
  </connectionstrings>

然后在webform_1.x.cs里面获取连接字符串,要添加如下引用;

using system.configuration;
using system.data;
using system.data.sqlclient;

 

代码:

sqlconnection con;


        protected void page_load(object sender, eventargs e)
        {
            connectdb();
        }

private void connectdb()
        {
            string constring = configurationmanager.connectionstrings["connectionstring"].connectionstring;
            con = new sqlconnection(constring);
            con.open();
            sqlcommand com = new sqlcommand();
            sqldatareader sdr;
            string sqlstr = "select * from item";
            com.commandtext = sqlstr;
            com.connection = con;
            sdr = com.executereader();
            while (sdr.read())
            {
                response.write(sdr["字段名"].tostring()+"</br>");
            }
            sdr.close();
            sdr = null;
           
        }