![ADO.NET SqlCommand功能 - Star99 - Star99的地盘 ADO.NET SqlCommand功能 - Star99 - Star99的地盘](http://img0.ph.126.net/JbeiDLY6DuVVTAoZBsDLTw==/2042663906089337112.png)
public static void AddData()
{
int res = -1;
//1.连接通道的连接字符串
string str = "server=.;database =test;uid=sa;pwd=chy19900909";
//2.连接通道对象
SqlConnection conn = new SqlConnection(str);
//string sql = "insert into [User] values (2,'chengyuan',23,null)"; //易错点:如果数据库表名是User这样的关键词要注意加[]
string sql2 = "insert into Name values(2,'chengyuan')";
SqlCommand cmd = new SqlCommand(sql2, conn);
//3.打开通道
conn.Open();
res = cmd.ExecuteNonQuery();
//关闭通道
conn.Close();
if (res > 0)
{
Console.WriteLine("数据库更新成功");
}
else
{
Console.WriteLine("数据库更新失败");
}
Console.ReadKey();
}
![ADO.NET SqlCommand功能 - Star99 - Star99的地盘 ADO.NET SqlCommand功能 - Star99 - Star99的地盘](http://img2.ph.126.net/6UDcdaErk4z6E2aXcrtmgQ==/6598169278285787441.png)
public static void QuerySingle()
{
SqlConnection con = new SqlConnection(conStr);
//string sqlStr = "select count(*) from Book";
string sqlStr = "select * from Book";
SqlCommand cmd = new SqlCommand(sqlStr, con);
con.Open();
//调用此方法,获得查询语句在数据库执行后得到的结果集的第一个单元格的值,返回类型是object
object obj = cmd.ExecuteScalar();
con.Close();
Console.WriteLine(obj.ToString());
}
![ADO.NET SqlCommand功能 - Star99 - Star99的地盘 ADO.NET SqlCommand功能 - Star99 - Star99的地盘](http://img0.ph.126.net/uAPkh3BTblDG89_XZQaeCA==/888335026599226764.png)
![ADO.NET SqlCommand功能 - Star99 - Star99的地盘 ADO.NET SqlCommand功能 - Star99 - Star99的地盘](http://img2.ph.126.net/fc3TEklxMKd_F5JztIU8bg==/3329567499610594322.png)
public static void QueryListByDrIndex() //查询多行数据--DataReader,逐行读取,通过下标访问列
{
SqlConnection con = new SqlConnection(conStr);
string sqlStr = "select * from Book";
SqlCommand cmd = new SqlCommand(sqlStr, con);
con.Open();
//调用此方法 获得一个 读取器对象
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)//如果结果集有数据行,则为true,否则为false
{
while (dr.Read())//read方法,如果读到下一行数据,则返回true,而且dr本身就等于那一行数据
{
Console.WriteLine(dr[0].ToString() + "_" + dr[1].ToString() + "_" + dr[2].ToString());
}
}
else Console.WriteLine("无数据");
dr.Close();//关闭读取器
con.Close();//关闭连接通道
}