C#数据库连接(代码连接)

aspx

  
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="cno">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"cno")%>
<%#DataBinder.Eval(Container.DataItem,"cname")%>
<%#DataBinder.Eval(Container.DataItem,"ccredit")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


cs

  
    string strConn = WebConfigurationManager.ConnectionStrings["i05ConnectionString2"].ToString();
SqlConnection ConnAcc
= new SqlConnection(strConn); //Sql链接类的实例化
ConnAcc.Open(); //打开数据库
string strSQL = "SELECT * FROM course"; //要执行的SQL语句
SqlDataAdapter da = new SqlDataAdapter(strSQL, ConnAcc); //创建DataAdapter数据适配器实例
DataSet ds = new DataSet(); //创建DataSet实例
da.Fill(ds, "112233"); //使用DataAdapter的Fill方法(填充),调用SELECT命令
GridView1.DataSource = ds; //设置数据源
GridView1.DataBind(); //绑定数据
ConnAcc.Close(); //关闭数据库


web.config

  
    <connectionStrings>
<add name="i05ConnectionString" connectionString="Data Source=localhost;Initial Catalog=i05;
    Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="i05ConnectionString2" connectionString="Data Source=aidd2008;
    Initial Catalog=i05;User ID=i05;Password=i05630229"
providerName="System.Data.SqlClient" />
</connectionStrings>

 

你可能感兴趣的:(数据库连接)