ADO.NET 基础
connectionString:
server=计算机名或ip\实例名;database=数据库名;uid=sa;pwd=密码; //Server authentication: SQL Server and Window Authentication Mode
server=计算机名或ip\实例名;database=数据库名;integrated security=true; // winForm 和 webForm 有所区别: 当前登录用户 和 其宿主环境提供的用户(ASPNET或NetWork Service等)
//可填充Dataset中的表数据
public static DataTable ExecuteDataTable(string sql, CommandType cmdType, params SqlParameter[] sparams)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.SelectCommand.CommandType = cmdType;
if (sp != null)
{
da.SelectCommand.Parameters.AddRange(sparams);
}
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
//获取执行结果,可以以此推写相关方法
public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] cmdParams)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = cmdText;
cmd.CommandType = cmdType;
if (cmdParams != null)
{
foreach (SqlParameter sp in cmdParams){
cmd.Parameters.Add(sp);
}
}
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}