黑马程序员 关于连接数据的基础操作(个人小结)

来源:互联网 发布:程序员必备的物品 编辑:程序博客网 时间:2024/05/29 18:45
------- Windows Phone 7手机开发、.Net培训、期待与您交流! -------

引入命名空间usingSystem.Data.SqlClient;

定义连接字符串

定义SqlConnection对象,并使用Open()方法打开对数据库的连接。

定义SqlCommand对象,并指定使用哪个连接对象连接到数据库。

定义SqlCommand对象使用何种SQL命令

使用SqlCommand对象的方法获得数据库中的数据并放入结果集中

使用SqlDataReader对象的方法将结果集中的数据读取出来加以操作

关闭数据库连接,用Close()方法。

注:在创建以上对象的实例的时候,可以using(){}结束后自动关闭,释放内存。

一、SqlConnection创建连接:

SqlConnection conn = new SqlConnection(“连接字符串”);

conn.Open();打开连接

二、SqlCommand对象

SqlCommand cmd = new SqlCommand();

cmd.CommandText = “要执行的SQL语句”; //可以用SqlCommand cmd = new SqlCommand(SQLCMD,CONN):SQLCMD为要执行的SQL语句,CONN为打开SqlConnection类的对象。另:SqlCommand cmd = conn.CreateCommand()与上面两个方法效果一样,只是写法不同。

cmd.ExecuteNonQuery();//执行命令但不返回任何结果集(唯一返回的是语句执行所影响的行数,数据类型为INT,一般用于InsertUpdata Delete),如果想从数据库调用数据则用:cmd.ExecuteReader(),返回结果集,里面的数据类型为Object。Cmd.ExcuteScalar()返回结果集中的第一行第一列。

在用VS自带的数据库的时候最好在要连接页面的地方加上:

    string dataDir = AppDomain.CurrentDomain.BaseDirectory;      if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release")) {           dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;           AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);      }  

例:

    using(SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True")){          conn.Open();          using (SqlCommand cmd = conn.CreateCommand()) {              cmd.CommandText = string.Format("INSERT INTO person(name,sex,age) values('{0}','{1}','{2}')", name, sex, i);              cmd.ExecuteNonQuery();          }      }  


public bool DataReaderEmail(string yhm,string maild)          {              using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))              {                  conn.Open();                  SqlCommand cmd = new SqlCommand(string.Format("select Mail from UserRegister where UserName='{0}' and Mail='{1}'", yhm, maild), conn);                  SqlDataReader sdr = cmd.ExecuteReader();                  if (sdr.Read())                  {                      return true;                  }                  else                  {                      return false;                  }              }  


------- Windows Phone 7手机开发、.Net培训、期待与您交流! -------