//using。Net中用来简化资源释放的一个关键字,把一个实现IDisposeble接口的对象进行资源回收
//using(类型 d=new ..)
//{.......}
//SqlConnection为建立和数据库连接的对象
using(SqlConnection conn=new SqlConnection(
"Data Source=127.0.0.1; Initial Catalog=高校信息管理; User ID =sa;PassWord=sa"))
{
conn.Open();//打开连接
///通过连接创建一个向数据库发命令(Command)的对象SqlCommand
using(SqlCommand cmd=conn.CreateCommand())
{
//CommandText为要执行的SQL语句.
cmd.CommandText = "insert into T_Student(Name,Age) values('元芳',22)";
cmd.ExecuteNonQuery();//执行
}
}
using (SqlConnection conn = new SqlConnection(
"Data Source=127.0.0.1;Initial Catalog=高校信息管理;User ID =sa;PassWord=sa"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select count(*) from T_Student where Age>20";
var count = cmd.ExecuteScalar();
MessageBox.Show(count.ToString());
}
}
using (SqlConnection conn = new SqlConnection(
"Data Source=127.0.0.1; Initial Catalog=高校信息管理; User ID =sa;PassWord=sa"))
{
conn.Open();//打开连接
///通过连接创建一个向数据库发命令(Command)的对象SqlCommand
using (SqlCommand cmd = conn.CreateCommand())
{
// <span style="color:#ff6666;">output inserted.id用于获取插入数据的ID值</span>,可为其他字段。也可在SQLServer里面执行该语句
cmd.CommandText = "insert into T_Student(Name,Age) output inserted.id values('元芳',22)";
var id = cmd.ExecuteScalar();//执行
MessageBox.Show(id.ToString());
}
}