C#连接数据库

来源:互联网 发布:海洋cms仿迅影网模板 编辑:程序博客网 时间:2024/06/05 08:24

<span style="font-size:24px;">在要在应用程序中访问数据库中的数据,首先要建立连接。以下是应用程序与SQLServer数据库连接的代码及详细解释:</span><pre name="code" class="csharp">using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.SqlClient;namespace XMLRW{    public partial class conn : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            //首先创建连接字符串,数据源:本地用“.”Initial Catalog 为连接数据库的名字;uid则为数据库名称,后面为数据库密码            string strcon = "Data Source=.;Initial Catalog = Message;uid = sa;pwd = 123123";            using (SqlConnection conn = new SqlConnection(strcon))    //使用using实例化连接            {                conn.Open();        //打开连接                SqlCommand comm = new SqlCommand();                comm.Connection = conn;         //实例化SqlCommand类并将其与数据库连接                string sql = "select * from Menu";  //查询Menu的信息                comm.CommandText = sql;             //与数据库查询连接                SqlDataAdapter sqlAdapter = new SqlDataAdapter();       //实例化适配器                sqlAdapter.SelectCommand = comm;                //适配器与SqlCommand连接                conn.Close();       //关闭连接            }        }    }}




0 0
原创粉丝点击