static void Main(string[] args)
{
string conString = @“Server="//地址
+ "DataBase=***;"//数据库的名称
+ "Uid=;pwd=”;//数据库账号与密码
#region 连接数据库
创建连接对象
//SqlConnection conn = new SqlConnection(conString);
打开连接数据库
//conn.Open();
判断是否已经连接上数据库
//if (conn.State == ConnectionState.Open)
// Console.WriteLine("成功连接上数据库");
//else
// Console.WriteLine("连接数据库失败!");
//conn.Close();//关闭连接数据库
//if (conn.State == ConnectionState.Closed)
// Console.WriteLine("成功关闭数据库");
//else
// Console.WriteLine("关闭数据库失败!");
//Console.ReadKey();
#endregion
#region 增加数据
创建连接对象
SqlConnection conn = new SqlConnection(conString);
构建SQL语句
string sql = "insert into Student(Student_ID,Student_Name,Student_Sex,Phone_Number)values(5, '龙嗷', '男', '123-456')";
//创建一个SqlCommand对象 传入连接对象与执行SQL的代码
SqlCommand cmd = new SqlCommand(sql, conn);
//打开连接数据库
conn.Open();
//执行SQL语句---执行SQL语句并返回受影响的行
int result = cmd.ExecuteNonQuery();
//关闭数据库
conn.Close();
//判断返回受影响的行的数量
if (result == 1)
Console.WriteLine("插入成功");
else
Console.WriteLine("插入失败");
#endregion
#region 删除某行
创建连接对象
//SqlConnection conn = new SqlConnection(conString);
构建SQL语句
//string sql = "delete from Student where Student_ID=5";
创建一个SqlCommand对象 传入连接对象与执行SQL的代码
//SqlCommand cmd = new SqlCommand(sql, conn);
打开连接数据库
//conn.Open();
执行SQL语句---执行SQL语句并返回受影响的行
//int result = cmd.ExecuteNonQuery();
关闭数据库
//conn.Close();
判断返回受影响的行的数量
//if (result >= 1)
// Console.WriteLine("删除成功");
//else
// Console.WriteLine("删除失败");
#endregion
#region 查询数据
创建连接对象
//SqlConnection conn = new SqlConnection(conString);
构建SQL语句
//string sql = "select * from Student";
创建一个SqlCommand对象 传入连接对象与执行SQL的代码
//SqlCommand cmd = new SqlCommand(sql, conn);
打开连接数据库
//conn.Open();
数据库读取类- [只读形式] 读取返回的结果
//SqlDataReader objReader = cmd.ExecuteReader();
==============================================
//while (objReader.Read())//判断下一行是否有数据,如果有为True否False
//{
// Console.WriteLine("{0}\t{1}\t{2}\t{3}",
// objReader["Student_ID"],
// objReader["Student_Name"],
// objReader["Student_Sex"],
// objReader["Phone_Number"]
// );
//}
//objReader.Close();
//conn.Close();
#endregion
#region 修改数据
//创建连接对象
//SqlConnection conn = new SqlConnection(conString);
//构建SQL语句
//string sql = "UPDATE Student set Student_Name='拉格纳罗斯',Student_Sex='女',Phone_Number = '456-789' where Student_ID = 1";
创建一个SqlCommand对象 传入连接对象与执行SQL的代码
//SqlCommand cmd = new SqlCommand(sql, conn);
打开连接数据库
//conn.Open();
执行SQL语句---执行SQL语句并返回受影响的行
//int result = cmd.ExecuteNonQuery();
关闭数据库
//conn.Close();
判断返回受影响的行的数量
//if (result >= 1)
// Console.WriteLine("修改成功");
//else
// Console.WriteLine("修改失败");
#endregion
Console.ReadKey();
}
}