/*
连接数据库步骤--
1.创建连接字符串
data source = ... 计算机名称
initial catalog = ... 数据库名称
integrated security = true windows系统
2.创建连接对象
3.打开连接(如果打开数据连接没有问题,表示连接成功)
4.关闭连接,释放资源
*/
class Program
{
static void Main(string[] args)
{
string constr = "data source = localhost;initial catalog = HaHahaha;integrated security = true";
/*string constr = "data source = localhost;initial catalog = ITCAST2014;userid = sa;password = *******";
*/
using(SqlConnection con = new SqlConnection(constr))
{
con.Open();
Console.WriteLine("打开连接成功");
}
Console.WriteLine("关闭连接,释放资源");
Console.ReadKey();
}
}
}


--------------------------------------------------------------------------------------------------------------------

#region 通过ado.net向表中插入一条数据
/*
//1.连接字符串
string constr = "data source = PIAOHUXIHU-PC;initial catalog = HaHahaha;integrated security = true";
//2.创建连接对象
using(SqlConnection con = new SqlConnection(constr))
{
//3.打开连接
con.Open();
//Console.WriteLine("连接打开成功!");
//4.编写sql语句
string sql = "insert into Employe values('政治部','男')";
//5.创建一个执行sql语句的对象(命令对象sqlcommand)
using (SqlCommand cmd = new SqlCommand(sql, con))
{
//6.开始执行sql语句
//ExecuteNonQuery();这个方法有一个返回值是int 类型,表示执行insert\delete\update语句后所影响的行数;
//特别的:ExecuteNonQuery()只有在执行insert\delete\update语句的时候,才会返回影响的行数,其他sql语句永远返回-1.
int r = cmd.ExecuteNonQuery(); //insert/delete/update
Console.WriteLine("成功插入一条语句");
//cmd.ExecuteScalar(); //当执行返回单个结果时
//cmd.ExecuteReader(); //当查询出多行,多列结果的时候
}
}
Console.ReadKey();
*/
#endregion



------------------------------------------------------------------------------------
#region 删除表中数据
//1.连接字符串
string constr = "data source = localhost;initial catalog = HaHahaha;integrated security";
//2.创建连接对象
using(SqlConnection con = new SqlConnection(constr))
{
//3.打开连接
con.Open();
//Console.WriteLine("成功打开表");
//4.编写sql语句
string sql = "delete from Employe where EmpId = 3";
//5.创建一个执行sql语句的对象
using(SqlCommand cmd = new SqlCommand(sql,con))
{
//6.执行sql语句
int r = cmd.ExecuteNonQuery();
Console.WriteLine("执行了一条语句!");
}

}
Console.ReadKey();


#endregion

posted on 2019-08-08 15:43  漂乎兮乎  阅读(1355)  评论(0编辑  收藏  举报