首先,使用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=\"Web\" /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语句时,它就会向对应的数据库执行操作。