ASP.NET连接SQL server数据库

首先,使用visual studio创建ASP.NET Web 应用程序(.NET Framework)项目

然后找到Web.config文件中,添加<connectionStrings>,其中,name属性可以自己取名字,connectionString属性中server=.是指连接本地数据库,你也可以写127.0.0.1,uid=sa是指连接数据库的用户名,pwd=123是指连接数据库的密码,database=usermessage是指连接数据库的名字。

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <connectionStrings>
	  <add name="sa" connectionString="server=.;uid=sa;pwd=123;database=usermessage"/>
  </connectionStrings>
</configuration>

 创建一个c#文件,用于连接数据库。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class MsSqlHelper
    {
        //从刚才的connectionStrings标签中,获取name=sa的数据库信息
        public static readonly string connectionString = ConfigurationManager.ConnectionStrings["sa"].ConnectionString;
        
        //sql形参为外部调用该方法时,传入的sql语句
        public static int AddSql(string sql)
        {
            //创建连接
            SqlConnection conn=new SqlConnection(connectionString);
            //执行传入的sql指令
            SqlCommand comm = new SqlCommand(sql,conn);
            try
            {
                conn.Open();
                //返回执行后的结果
                return Convert.ToInt32(comm.ExecuteNonQuery());
            }
            catch (Exception ex)
            {
                conn.Close();
                throw new Exception(ex.Message);
            }  
        }
    }
}

当对其传入一个sql语句时,它就会向对应的数据库执行操作。

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值