1 我们一般执行插入,删除等这些对数据库的操作会影响到数据表的行数,可用以下代码
Code
string strConn = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = strConn;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into TestTable values(name,age)";
int row = cmd.ExecuteNonQuery();
}
2.返回查询结果的两种
Code
string strConn = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = strConn;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select *from TestTable";
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
}
Code
string strConn = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = strConn;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select *from TestTable";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = conn;
DataSet ds =new DataSet();
da.Fill(ds, "data");
// 这里ds.Tables["data"];里就是查询结果
}