连接字符串
- server:表示连接的服务
- uid:sqlserver用户名
- pwd:密码
- database:表示要连接的数据库
cmd
- cmd.ExecutrScalar() 返回查询结果的第一行第一列的值
配置文件配置连接字符串
/* App.config */
<configuration>
<connectionString>
<add name="sql" connectionStrings="server=.;uid=sa;pwd=123456;database=demo"/>
</connectionString>
</configuration>
//获得配置文件中的AppSetting中的数据
string connStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
DataSet和DataTable
// 创建一个内存的数据集
DataSet ds = new DataSet("DSS");
// 创建一张内存表
DataTable dt1 = new DataTable("dt1");
//把表放到数据集里面去
ds.Tables.Add(dt1);
// 给表定义列
DataColumn dcName = new DataColumn("Name",typeof(string));
// 把列放到表里面去
dt1.Colums.AddRange(new DataColumn[ ] {dcIName});
//给表添加数据
dt1.Rows.Add("陈莹");
SqlHelper封装
public class SqlHelper
{
// 获取连接字符串
public static string GetSqlConnectionString()
{
return ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
}
// 封装一个执行sql返回受影响的行数
public static int ExcuteNonQuery(string sqlText, params SqlParameter[] parameters)
{
using(GetSqlConnection conn = new GetSqlConnection(GetSqlConnectionString()))
{
using(SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlText;
cmd.Parameters.AddRange(parameters);//参数添加到cmd命令中
return cmd.ExecuteNonQuery();
}
}
}
//执行sql,返回查询结果中的第一行第一列的值
public static object ExcuteScalar(string sqlText, params SqlParameter[] parameters)
{
using(GetSqlConnection conn = new GetSqlConnection(GetSqlConnectionString()))
{
using(SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlText;
cmd.Parameters.AddRange(parameters);
return cmd.ExcuteScalar();
}
}
}
//执行sql,返回一个DataTable
public static DataTable ExcuteDataTable(string sqlText, params SqlParameter[] parameters)
{
using(SqlDataAdapter adapter = new SqlDataAdapter(sqlText, GetSqlConnectionString()))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
//执行sql,返回一个SqlDataReader
public static SqlDataReader ExcuteReader(string sqlText, params SqlParameter[] parameters)
{
//SqlDataReader要求,在在读取数据时,独占SqlConnection对象,SqlConnection必须是Open状态
SqlConnection conn = new SqlConnection(GetSqlConnectionString());
SqlCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = sqlText;
cmd.Parameters.AddRange(parameters);
//当SqlDataReader释放时,把SqlConnection对象也释放掉
return cmd.ExcuteReader(CommandBehavior.CloseConnection);
}
}