标签:sub HERE ext sqlserver connect rate reader str sql
DO.NET 由.Net Framework 数据提供程序和DataSet 两部分构成.
.NET FrameWork 是
Connection 连接对象
Command 命令对象
DataReader 阅读器对象
DataAdapter 适配器对象
四个核心对象构成。
使用是SqlServer数据库,所以,命令空间为
System.Data.Sqlclient
四个核心对象需加前缀
SqlConnection
SqlCommand
SqlDataReader
SqlDataAdapter
1、SqlConnection 是连接对象,创建应
用程序和数据库服务器之间的联接。
//连接字符串
string conString = “server=.;integrated security = sspi;database = MySchool”;
//创建连接
SqlConnection connection = new SqlConnection(conString);
//在应用程序中连接到数据库服务器。
方法:Open()打开连接
Close() 关闭连接
2、SqlCommand 命令对象,用于执行SQL语句并返回查询的结果集。
属性:
CommandText:要执行的SQL语句
Connection:连接对象
方法:
ExecuteScalar() ,查询聚合函数,返回单个值,返回类型为object.
ExecuteReader(),查询多行多列,返回一个结果集SqlDataReader对象。
ExecuteNonQuery() 用于执行增、删、改
等SQL语句,返回受影响的记录的条数。
返回类型为int
//示例
string selcmd = “select count(*) from userinfo”;
//创建命令对象
SqlCommand command = new SqlCommand(selcmd,connection);
//执行命令
object result = command.ExecuteScalar();
三种情况:
//1、连接字符串
string conString = “server=.;integrated security = sspi;database = MySchool”
//2、连接对象
SqlConnection connection = new SqlConnection(conString);
//3、打开连接
connection.Open();
//4、查询的SQL语句
string selcmd =string.Format(“select count(*) from student where loginid=’{0}’”,userName);
//5、命令对象
SqlCommand command = new SqlC ommand(selcmd,connection);
//6、执行命令
int res = Convert.ToInt32(command.ExecuteScalar());
2.查询多行多列
//1、连接字符串
string conString = “server=.;integrated security = sspi;database = MySchool”
//2、连接对象
SqlConnection connection = new SqlConnection(conString);
//3、打开连接
connection.Open();
//4、查询的SQL语句
string selcmd = “select studentno,studentname,gradeid,phone from student”;
//5、命令对象
SqlCommand command = new SqlC ommand(selcmd,connection);
//6、执行命令,得到SqlDataReader对象
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string no = reader[“StudentNo”].ToString();
string name = reader[“StudentName”].ToString();
Console.WriteLine(“{0}\t{1}”,no,name);
}
reader.Close();
connection.Close();
//1、连接字符串
string conString = “server=.;integrated security = sspi;database = MySchool”
//2、连接对象
SqlConnection connection = new SqlConnection(conString);
//3、打开连接
connection.Open();
//4、查询的SQL语句
string selcmd = “insert into subject values(‘easyui’,30,3)”;
//5、命令对象
SqlCommand command = new SqlC ommand(selcmd,connection);
//6、执行命令,得到结果
int res = command.ExecuteNonQuery();
//1、连接字符串
string conString = “server=.;integrated security = sspi;database = MySchool”
//2、连接对象
SqlConnection connection = new SqlConnection(conString);
//3、打开连接
connection.Open();
//4、查询的SQL语句
string selcmd = “insert into subject values(‘easyui’,30,3)”;
//5、命令对象
SqlCommand command = new SqlC ommand(selcmd,connection);
//6、适配器对象
SqlDataAdapter da = new SqlDataAdapter(command);
//7、数据集对象
DataSet ds = new DataSet();
//8、将数据填充到数据集
da.Fill(ds);
标签:sub HERE ext sqlserver connect rate reader str sql
原文地址:https://www.cnblogs.com/hackhyl/p/9532284.html