C#与数据库访问技术总结(七)综合示例
时间:2022-03-14 01:49
执行结果界面如图:
分析代码:
第1步是引入命名空间:System.Data.SqlClient,表示将使用SQL Server.NET 数据提供程序: using System.Data.SqlClient;
第2步是 按钮button1_Click单击事件中首先新建立了连接并设置了其连接字符串属性:
string connString="server=(local);Initial Catalog=Student;Integrated Security=SSPI;";
//string connString= "server=(local);user id=sa;Initial Catalog=Student;pwd=;";
//定义Connection对象
SqlConnection conn = new SqlConnection();
//设置Connection对象的ConnectionString属性
conn.ConnectionString = connString;
第三步,新建Command 对象,并将命名文本和连接对象传递给其构造函数:
SqlCommand cmd = new SqlCommand(commandText, conn);
其中,commandText为最初定义的命名文本:
string commandText = "select count(*) from studentInfo";
此时conn对象没有打开,因为这不是必须的。
第四步 现在需要执行操作了,所以首先要打开连接,然后执行操作:
conn.Open();
string count = cmd.ExecuteScalar().ToString();
由于ExecuteScalar()方法返回类型为object,因此使用了ToString()方法将其转换为string以后赋值给count。
注意:一般使用ExecuteScalar()方法时都必须用到类型转换。
第五步数据库访问完毕以后应该立即关闭连接,这是一个好习惯:
corm.Close();
第六步最后将读取的信息通过label1显示出来:
this.label1.Text="共有"+count+"位学生!";
上面的代码中并没有指定Command对象的CommandType属性,这时CommandType的值将为默认的Text,当然也可以通过如下代码显示指定其类型,但这不是必须的。
cmd.CommandType=CommandType.Text;