ITPub博客

首页 > Linux操作系统 > Linux操作系统 > c#连接SqlServer数据库

c#连接SqlServer数据库

原创 Linux操作系统 作者:wangping_cool 时间:2012-10-29 09:35:35 0 删除 编辑

首先在代码窗口导入"System.Data.SqlClient"命名空间

在连接字符串中,应该吧Persist Security I nfo设置为false(保证在使用信息打开连接后不可信的源无法访问到连接中涉及安全性的信息.)

有四个对象:Connection,Command,DataReader,DataAdapter

其中DataReader是应用程序读取数据源的数据流对象

Sqlconnection conn=new Sqlconnection(@"Server=ServerName;uid=sa;pwd=;DataBase=dbName");

也可以使用其ConnectionString属性

Sqlconnection conn=new Sqlconnection();

conn.ConnectionString=@"Server=ServerName;uid=sa;pwd=;DataBase=DataBaseName";

Commend对象的属性:①有CommendTye,它有3中取值CommendType.Text,表明是普通sql语句,也是默认值;CommendType.TableDirect,表明是数据表名;Commend.Type.StoreProcedure,表明是存储过程.

②:CommendText:它的值是sql语句或者数据表名或者存储过程名称.

方法有:①Connection:它的值是Commend对象使用的connection对象名称②ExecuteReader:他的值指执行sql命令后返回一个包含数据的DataReader对象③ExecuteNonQuery计算当执行了一个非查询操作后所影响的记录数字.④ExecuteScalar:执行查询,并返回结果数据集合的第一行第一列的值.⑤Dispose:关闭Commend对象释放所占系统资源

实例1:

SqlConnection conn=new SqlConnection();
            conn.ConnectionString=@"Server=BeiHai;uid=sa;pwd=sa;database=studentDb";
            String connStr = conn.ConnectionString;
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = connStr;
            cmd.CommandText = "select * from student order by id";
            cmd.CommandType = cmd.CommandText;
            SqlDataReader dr = cmd.ExecuteReader();
            gv.DataSource = dr;
            gv.DataBind();
            dr.Close();

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28311102/viewspace-747802/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: .Net技术网址
请登录后发表评论 登录
全部评论

注册时间:2012-10-26

  • 博文量
    8
  • 访问量
    17580