通过ado.net连接数据库

转载请声明出处:https://blog.csdn.net/cyzhah/article/details/82503318

一、连接数据库的步骤:

1、创建连接字符串

//Data Source =         //连接的数据库实例

//Initial Catalog =      

//Integrated Security  = true;

string constr = "Data Source=steve-pc;Initial Catalog=itcast2014;UserID=sa;Password=123";

string constr = "Data Source=steve-pc;Initial Catalog=itcast2014;Integrated Security  = true"(上面的也可以)

2、创建连接对象

using(sqlConnection con = new sqlConnection(constr))

{

扫描二维码关注公众号,回复: 3411077 查看本文章

  3、打开连接(如果打开数据连接没问题,表示连接成功!)

con.Open();

4、关闭连接,释放资源

//con.Close();

//con.Dispose();

}

二、通过ado.net向表中进行增、删、改、查

//1.连接字符串

string constr = "Data Source = STEVE-PC; Initial Catalog = itcast2014;Integrated Security = True";

//2、创建连接对象

using(sqlConnection con = new sqlConnection(constr))

{

//3、编写sql语句

string sql = "insert into TblPerson values('xxx',10,111,1)"; // 插入一条数据

string sql = "delete from Tbperson where autoId = 3";//删除一条数据

string sql = "update  TblPerson set uName = ‘橙子’,age = 20,height= 176 where autoId = 44";  //修改操作

string sql = select count(*) from Student; //查询表中的记录条数

//4.创建一个执行sql语句的对象

using (sqlCommand cmd = new sqlCommand(sql,con))

{

//5、打开连接

con.Open();

//6、开始执行sql语句

//(ExecuteNonQuery()这个方法有一个返回值是int类型,表示执行insert、delete、update语句后

所影响的行数。特别注意:ExecuteNonQuery()只有执行insert、delete、update语句的时候会返回所影响的行数,执行任何其他sql语句永远返回-1)

cmd.ExecuteNonQuery();//执行insert、delete、update语句时

//cmd.ExecuteScalar();//当执行返回单个结果的时候

//cmd.ExecuteReader();//当查询出多行,多列结果的时候

}

}

猜你喜欢

转载自blog.csdn.net/cyzhah/article/details/82503318