.NET 数据库配置链接

本文介绍了.NET数据库配置的步骤,包括引入命名、配置config文件以及进行增删改查操作的基础教程,适合初学者掌握数据库连接操作。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、使用步骤

1.引入命名

代码如下(示例):

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

2.配置config

代码如下(示例):

 <connectionStrings>
    <add name="StudentCnnString" connectionString="Data Source=PC-16;
         Initial Catalog = Student;
         Integrated Security = True;
         User Instance = False;"
         providerName =" System.Data.SqlClient"/>
  </connectionStrings>

3.增删改查操作

   public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source = PC-16; Initial Catalog=Student; Integrated Security = True;");
        con.Open();
        Response.Write("连接成功");
        con.Close();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        string strCon = ConfigurationManager.ConnectionStrings["StudentCnnString"].ConnectionString;
        SqlConnection con = new SqlConnection(strCon);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Insert into UserInfo(UserId,Password) values('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "');";

        try
        {
            con.Open();
            Response.Write("连接成功");
        }
        catch (Exception ex)
        {
            Response.Write("链接失败,原因为 " + ex.Message);
        }
        finally
        {
            if (con.State == ConnectionState.Open) con.Close();
        }
    }

    //修改数据


    protected void Button2_Click1(object sender, EventArgs e)
    {
        string strCon = ConfigurationManager.ConnectionStrings["StudentCnnString"].ConnectionString;
        SqlConnection con = new SqlConnection(strCon);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Update UserInfo set Password='" + TextBox2.Text.Trim() + "' where UserId='" + TextBox2.Text.Trim() + "'";

        try
        {
            con.Open();
            int re = cmd.ExecuteNonQuery();
            if (re > 0)
                Response.Write("修改密码成功");
            else Response.Write("不存在用户名:" + TextBox1.Text);
        }
        catch (Exception ex)
        {
            Response.Write("链接失败,原因为 " + ex.Message);
        }
        finally
        {
            if (con.State == ConnectionState.Open) con.Close();
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        string strCon = ConfigurationManager.ConnectionStrings["StudentCnnString"].ConnectionString;
        SqlConnection con = new SqlConnection(strCon);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "delete From UserInfo where UserId = '" + TextBox2.Text.Trim() + "'";

        try
        {
            con.Open();
            int re = cmd.ExecuteNonQuery();
            if (re > 0)
                Response.Write("删除成功");
            else Response.Write("不存在用户名:" + TextBox1.Text);
        }
        catch (Exception ex)
        {
            Response.Write("链接失败,原因为 " + ex.Message);
        }
        finally
        {
            if (con.State == ConnectionState.Open) con.Close();
        }
    }
    //连接模式查询
    protected void Button4_Click(object sender, EventArgs e)
    {
        {
            string strCon = ConfigurationManager.ConnectionStrings["StudentCnnString"].ConnectionString;
            SqlConnection con = new SqlConnection(strCon);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "Select * from StuInfo;";
            SqlDataReader sdr = null;

            try
            {
                con.Open();
                sdr = cmd.ExecuteReader();
                GridView1.DataSource = sdr;
                GridView1.DataBind();

            }
            catch (Exception ex)
            {
                Response.Write("shaxun失败,原因为 " + ex.Message);
            }
            finally
            {
                if (con.State == ConnectionState.Open) con.Close();
            }
        }
    }
}

 //断开模式查询数据
    protected void Button2_Click(object sender, EventArgs e)
    {
        string strCnn = ConfigurationManager.ConnectionStrings["StudentCnnString"].ConnectionString;
        SqlConnection con = new SqlConnection(strCnn);
        SqlDataAdapter sda = new SqlDataAdapter("select * from StuInfo;", con);

        DataTable dt = new DataTable();
        try
        {
            sda.Fill(dt);
            GridView2.DataSource = dt;
            GridView2.DataBind();
        }
        catch (Exception ex)

        {
            Response.Write("shaxun失败,原因为 " + ex.Message);
        }
    }

添加了两个botton

总结

基础中的基础,数据库连接操做

### ASP.NET配置数据库连接字符串的方法 在 ASP.NET 应用程序中,配置数据库连接字符串是一个常见的需求。以下是关于如何正确设置和使用数据库连接字符串的详细介绍。 #### 1. 使用 `Web.config` 文件存储连接字符串 为了提高应用程序的安全性和可维护性,通常会将连接字符串存放在项目的 `Web.config` 或 `App.config` 文件中。通过这种方式,可以在运行时动态读取连接字符串而无需硬编码到代码中。 示例 `Web.config` 的部分配置如下: ```xml <configuration> <connectionStrings> <add name="PrimarySchoolDB" connectionString="server=BL48VQ68YDRNQMN\SQLEXPRESS;database=PrimarySchool;user id=admin;password=123456;" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> ``` 上述配置定义了一个名为 `PrimarySchoolDB` 的连接字符串[^1]。 #### 2. 动态获取连接字符串 可以通过 `ConfigurationManager` 类来访问存储在 `Web.config` 文件中的连接字符串。具体实现方法如下: ```csharp using System.Configuration; string connStr = ConfigurationManager.ConnectionStrings["PrimarySchoolDB"].ConnectionString; ``` 此代码片段展示了如何从配置文件中提取名称为 `PrimarySchoolDB` 的连接字符串[^2]。 #### 3. 构建灵活的连接字符串 如果需要构建更加灵活的连接字符串,则可以利用 `SqlConnectionStringBuilder` 类。该类允许开发者逐项设置连接参数并最终生成完整的连接字符串。 下面是一段演示代码: ```csharp using System.Data.SqlClient; var builder = new SqlConnectionStringBuilder(); builder.DataSource = "BL48VQ68YDRNQMN\\SQLEXPRESS"; builder.InitialCatalog = "PrimarySchool"; builder.UserID = "admin"; builder.Password = "123456"; string connectionString = builder.ConnectionString; ``` 在此例子中,`DataSource` 属性被赋值为服务器地址,这相当于标准连接字符串中的 `Data Source` 参数[^3]。 #### 4. 连接 MySQL 数据库 除了 SQL Server 外,在 ASP.NET 中也可以轻松地与 MySQL 数据库建立连接。此时需注意调整驱动程序以及相应的连接字符串格式。 MySQL 的典型连接字符串形式如下所示: ```csharp string mySqlConnectionStr = "Server=localhost;Database=testdb;Uid=root;Pwd=mypassword;"; ``` 对于基于配置文件的方式,同样适用类似的逻辑去加载连接信息[^4]。 #### 5. 特殊场景下的本地数据库支持 当项目依赖于 Visual Studio 自带的 LocalDB 实现轻量级数据操作时,其对应的连接字符串可能形如以下内容: ```csharp string localDbConnStr = @"Server=(localdb)\mssqllocaldb;Integrated Security=true;AttachDbFileName=C:\Path\To\Database.mdf"; ``` 这里指定了 `(localdb)` 和实例名 `\mssqllocaldb` 来表明正在使用的是一种嵌入式的数据库引擎[^5]。 --- ### 总结 以上介绍了多种情况下 ASP.NET 配置数据库连接字符串的技术细节及其实际应用案例。无论是针对传统的 SQL Server 数据源还是现代跨平台解决方案(例如 MySQL),都可以找到合适的实践路径。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值