谁能提供一下SQL servers 与ASP.NET最好的连接代码?
尽量加上注释哈
尽量加上注释哈
答案:using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace CarLeaseDAL
{public class SQLHelp{static string sqllj = "server=SQL服务器名;database=数据库;uid=用户名;pwd=密码"; public DataTable Select(string sql) { using (SqlConnection _sqlconn = new SqlConnection(sqllj)){using (SqlDataAdapter _sqlda = new SqlDataAdapter(sql, _sqlconn)){using (DataSet ds = new DataSet()){_sqlda.Fill(ds);return ds.Tables[0];}}}}public bool AddRevise(string sql){using (SqlConnection _sqlcon = new SqlConnection(sqllj)){using (SqlCommand _sqlcom = new SqlCommand(sql, _sqlcon))
{
try
{
_sqlcon.Open();
int gj = _sqlcom.ExecuteNonQuery();
if (gj > 0)
{
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
throw ex;
// return false;
}
finally
{
_sqlcon.Close();
}
}
}
}
public SqlDataReader Datareader(string sql)
{
SqlConnection _sqlcon = new SqlConnection(sqllj);
SqlCommand _sqlcomd = new SqlCommand(sql,_sqlcon);
SqlDataReader da = null;
try
{
_sqlcon.Open();
da = _sqlcomd.ExecuteReader(CommandBehavior.CloseConnection);
return da;
}
catch
{
return null;
}
}
dim conn,connstr,rs '定义变量conn,connstr,rs
set rs=server.createobject("adodb.recordset") '打开rs
set conn=server.cresteobject("adodb.connection") '打开conn是一个连接名
connstr="driver={sql server};server=(local);"&"uid=sa;pwd=;datebase=数据库名"
‘数据库类型是sql server 服务器是本机(local) uid是用户登录名 pwd为装sql server时的密码 database是你建立的数据库的名称
conn.open connstr
’用数据库连接对象 conn的open方法打开 connstr中指定的数据库在web.config文件中添加:
<connectionStrings>
<add name="连接字符 " connectionString="Server=local;Database=db_Login;User id=sa;Password=123456;" />
</connectionStrings>
在所用asp网页的后置代码中即.cs文件中添加
string mystr = ConfigurationManager.ConnectionStrings["连接字符"].ConnectionString;
SqlConnection con = new SqlConnection(mystr);
con.open();SqlConnection conn = new SqlConnection("Server=(local);Database=BOOKMIS;uid=sa;pwd=123;");在web.config里设置:
<configuration>
<appSettings>
<add key="ConnectionString" value="server=.;database=你的数据库名;uid=sa;pwd=你的数据库密码"/>
</appSettings>
<connectionStrings/>您是要数据访问层,还是要连接字符串?
数据访问层的话建议用mic的企业库sqlhelper.cs
连接字符串的话(没有最好的说法)连接本机的字符串
<appSettings>
<add key="ConnectionString1" value="server=.;database=databasename;uid=sa;pwd=sa" />
<add key="ConnectionString2" value="server=(local);database=databasename;uid=sa;pwd=sa" />
<add key="ConnectionString3" value="server=127.0.0.1;database=databasename;uid=sa;pwd=sa" />
<add key="ConnectionString4" value="server=您机器的IP;database=databasename;uid=sa;pwd=sa" />
</appSettings>sqlconnection conn=new sqlconnection("server=.;database=northwind;uid=sa;pwd=1234");定义连接通道
sqldataadapter da=new sqldataadapter("select * from 表名",conn);定义搬运工
DataSet ds=new DataSet();定义数据集
上一个:asp椤甸潰濡備綍鐢ㄤ唬鐮侊紙c#璇█锛夊疄鐜版墦鍗板姛鑳斤紵 - 宸茶В鍐?- 鎼滄悳闂棶
下一个:怎么才能把下面代码保存为1.asp的格式