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

------- 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培训、期待与您交流! -------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值