这个留言本使用的数据库是access 2003,当然你也可以以sql server 2k来做。程序只有3个文件,default.aspx主要用来展示留言及书写留言,checkcode.aspx是验证码的代码文件,admin.aspx 用来管理留言部分,我写的很简单,就是一个功能,删除。

sql部分,为了避免sql注入的威胁,我使用了oledbparameters来引入参数。现在我把代码贴出来,供那些正在学习c#,有志于学习c#的朋友参考一下,代码如果有什么漏洞,大家可以提出来。总之,就是一个目的,共同学习。

本留言本的在线实例: http://et.bestzhou.org/
以下代码仅供学习试验,请勿使用于生产环境.

default.aspx 文件代码

<%@ page language=”c#” autoeventwireup=”true”  codefile=”default.aspx.cs” inherits=”_default” %>  
<!doctype html public “-//w3c//dtd xhtml 1.0 transitional//en” “http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd”>  
<html xmlns=”http://www.w3.org/1999/xhtml” >  
<head runat=”server”>  
    <title>atlansing guestbook v1.0 beta</title>  
    <link href=”style.css” rel=”stylesheet” type=”text/css” />  


    <form id=”form1″ runat=”server”>  
    <div id=”pagediv”>  
    <div id=”msglist” runat=”server”>  
        <asp:gridview id=”gridview1″ autogeneratecolumns=”false” runat=”server”  width=”70%” allowpaging=”true” borderstyle=”none” borderwidth=”0px” cellpadding=”0″ showheader=”false” gridlines=”none”>  
            <columns>  
                <asp:templatefield showheader=”false”>  
                    <itemtemplate>  
                   <div id=”msgdiv”>  
                        <div class=”author”><asp:image id=”image1″ runat=”server” imagealign=”absmiddle” imageurl=”~/images/icon_quote.gif” /><strong><asp:hyperlink id=”author” runat=”server”  text=‘‘<%# eval(“author”) %>‘‘ navigateurl=‘‘<%# eval(“email”,”mailto:{0}”) %>‘‘></asp:hyperlink></strong>  
                            [ <asp:label id=”date” runat=”server” text=‘‘<%# eval(“date”) %>‘‘></asp:label> | <asp:label id=”ip” runat=”server” text=‘‘<%# eval(“ip”) %>‘‘></asp:label> ]</div>  
                           <div id=”msgcontent”><asp:label id=”msg” runat=”server” text=‘‘<%# eval(“msg”) %>‘‘></asp:label> </div>   
                    </div><br />  
                    </itemtemplate>  
                </asp:templatefield>  
            </columns>  
        </asp:gridview>  
       </div>   
       <div>  
        <table width=”80%” border=”0″ cellpadding=”0″ style=”text-align: left”>  
            <tr>  
                <td style=”text-align: right; width: 170px;”>昵称:</td>  
                <td style=”width: 292px”>  
                    <asp:textbox id=”author” runat=”server”></asp:textbox></td>  
                 <td style=”width: 130px”>  
                     <asp:requiredfieldvalidator id=”requiredfieldvalidator1″ runat=”server” controltovalidate=”author” errormessage=”*必须填写”></asp:requiredfieldvalidator></td>   
            </tr>  
            <tr>  
                <td style=”text-align: right; width: 170px;”>验证码:</td>  
                <td style=”width: 292px”>  
                    <asp:textbox id=”checkcode” runat=”server”></asp:textbox>  
                       <asp:image id=”image2″ runat=”server” imageurl=”~/checkcode.aspx” /></td>  
                 <td style=”width: 130px”>  
                     <asp:requiredfieldvalidator id=”requiredfieldvalidator3″ runat=”server” controltovalidate=”author” errormessage=”*必须填写”></asp:requiredfieldvalidator></td>   
            </tr>   
            <tr>  
                <td style=”text-align: right; width: 170px;”>email:</td>  
                <td style=”width: 292px; height: 20px”>  
                    <asp:textbox id=”email” runat=”server”></asp:textbox></td>  
&nbsp  
 ;                  <td id=”tablecell5″ runat=”server” style=”height: 20px; width: 130px;”>  
                       </td>    
            </tr>  
            <tr>  
                <td style=”text-align: right; width: 170px;”>website:</td>  
                <td style=”width: 292px”>  
                    <asp:textbox id=”website” runat=”server”></asp:textbox></td>  
                   <td id=”tablecell3″ runat=”server” style=”width: 130px”></td>    
            </tr>  
                       <tr id=”tablerow1″ runat=”server”>  
                <td id=”tablecell1″ runat=”server” style=”height: 80px; text-align: right; width: 170px;”>留言内容:</td>  
                <td id=”tablecell2″ runat=”server” style=”width: 292px; height: 80px”>  
                    <asp:textbox id=”msg” runat=”server” textmode=”multiline” height=”70px” width=”283px”></asp:textbox></td>  
                   <td id=”tablecell4″ runat=”server” style=”height: 80px; width: 130px;”>  
                       <asp:requiredfieldvalidator id=”requiredfieldvalidator2″ runat=”server” errormessage=”*必须填写” controltovalidate=”msg”></asp:requiredfieldvalidator></td>    
            </tr>   
           <tr>  
                <td style=”text-align: right; width: 170px;”></td>  
                <td style=”width: 292px”>  
                    <asp:button id=”savebtn” runat=”server” text=”发表留言” onclick=”savebtn_click” />   <asp:button id=”cancelbtn” runat=”server” text=”重写” />  
                    <asp:label id=”resultlbl” runat=”server” font-bold=”true” forecolor=”red”></asp:label>  
                </td>  
           </tr>   
        </table>  
           <br />  
           <br />  
           powered by <a href=”http://www.bestzhou.org/” title=”马上访问”>atlansing guestbook 1.0 beta</a><br />  
           copy © 2006-2007, bestzhou.org</div>  
    </div>  
    </form>  

default.aspx.cs 源代码文件

using system;  
using system.data;  
using system.data.sqlclient;  
using system.data.oledb;  
using system.configuration;  
using system.web;  
using system.web.security;  
using system.web.ui;  
using system.web.ui.webcontrols;  
using system.web.ui.webcontrols.webparts;  
using system.web.ui.htmlcontrols;  
using system.security.cryptography;</textarea>

public partial class _default : system.web.ui.page  
    {  
        public static string filename = “~//app_data//guestbook.mdb”;  
    public static string connstring = “provider=microsoft.jet.oledb.4.0; data source=” + system.web.httpcontext.current.server.mappath(filename);  
        protected void page_load(object sender, eventargs e)  
        {  
            oledbconnection odbconn = new oledbconnection(connstring);  
            oledbdataadapter dbada = new oledbdataadapter(“select * from [guestbook] order by [date] desc”, odbconn);  
            dataset ds = new dataset();  
            dbada.fill(ds);  
            gridview1.datasource = ds;  
            gridview1.databind();  
            if (gridview1.rows.count == 0)  
            {  
                gridview1.visible = false;  
                msglist.innerhtml = “<div style=”text-align:center”><strong>目前尚无新的留言</strong></div>”;  
            }  
            session.add(“ips”, request.userhostaddress);  
            if (ispostback != false)  
            {  
                gridview1.datasource = ds;  
           
        gridview1.databind();  
            }  
        }

        protected void savebtn_click(object sender, eventargs e)  
        {  
            savebtn.enabled = false;  
            if (string.compare(session[“checkcode”].tostring(), checkcode.text,true) == 0)  
            {  
                string myauthor = server.htmlencode(author.text);  
                //string mymsg = server.htmlencode(msg.text);  
                string mymsg = httputility.htmlencode(msg.text);  
                mymsg=mymsg.replace(“<b>”, “<b>”);  
                mymsg=mymsg.replace(“</b>”, “</b>”);  
                mymsg=mymsg.replace(“<i>”, “<i>”);  
                mymsg=mymsg.replace(“</i>”, “</i>”);  
                string myweb = server.htmlencode(website.text);  
                string myemail = server.htmlencode(email.text);  
                oledbconnection odbconn = new oledbconnection(connstring);  
                odbconn.open();  
                oledbdataadapter oleda = new oledbdataadapter(“select * from [guestbook] order by [date] desc”, odbconn);  
                try  
                {  
                    oledbcommand olecmd = new oledbcommand(“insert into [guestbook] (author,msg,email,website,ip) values (?,?,?,?,?)”, odbconn);  
                    oledbparameter p_author = olecmd.parameters.add(“@author”, oledbtype.varwchar, 12);  
                    p_author.value = myauthor;  
                    oledbparameter p_msg = olecmd.parameters.add(“@msg”, oledbtype.varwchar);  
                    p_msg.value = mymsg;  
                    oledbparameter p_email = olecmd.parameters.add(“@email”, oledbtype.varwchar);  
                    p_email.value = myemail;  
                    oledbparameter p_web = olecmd.parameters.add(“@web”, oledbtype.varwchar);  
                    p_web.value = myweb;  
                    oledbparameter p_ip = olecmd.parameters.add(“@ip”, oledbtype.varwchar);  
                    p_ip.value = session[“ips”].tostring();  
                    int i = olecmd.executenonquery();  
                    if (i != 0)  
                    {  
                        author.text = “”;  
                        email.text = “”;  
                        website.text = “”;  
                        msg.text = “”;  
                        checkcode.text = “”;  
                        savebtn.enabled = true;  
                        resultlbl.text = “保存留言成功”;  
                    }  
                }  
                catch(oledbexception ex)  
                {  
                    resultlbl.text = ex.message;  
                }  
                catch(exception ex)  
                {  
                    resultlbl.text=ex.message;  
                }  
          &  
 nbsp;      
                dataset ds = new dataset();  
                oleda.fill(ds);  
                odbconn.close();  
                gridview1.datasource = ds;  
                gridview1.databind();  
            }  
            else  
            {  
                resultlbl.text = “验证码错误”;  
                savebtn.enabled = true;  
                return;              
            }  
        }  
    }

checkcode.aspx 页面代码:

<%@ page language=”c#” autoeventwireup=”true” codefile=”checkcode.aspx.cs” inherits=”checkcode” %>  
<!doctype html public “-//w3c//dtd xhtml 1.0 transitional//en” “http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd”></textarea>

<html xmlns=”http://www.w3.org/1999/xhtml” >  
<head runat=”server”>  
    <title>无标题页</title>  
<!– 点击后退按钮,刷新验证码 –>  
<% response.buffer = true ;%>  
<% response.expiresabsolute = datetime.now.addseconds(-1);%>  
<% response.expires = 0 ;%>  
<% response.cachecontrol = “no-cache” ; %>  


    <form id=”form1″ runat=”server”>  
    <div>  
      
    </div>  
    </form>  

checkcode.aspx 源文件代码:

using system;  
using system.data;  
using system.configuration;  
using system.collections;  
using system.web;  
using system.web.security;  
using system.web.ui;  
using system.web.ui.webcontrols;  
using system.web.ui.webcontrols.webparts;  
using system.web.ui.htmlcontrols;  
using system.drawing;</textarea>

public partial class checkcode : system.web.ui.page  
{  
    //验证码由生成彩色验证码和zhongfeng, http://blog.csdn.net/sw515 的验证码综合而成.  
    //感谢他们的劳动.  
    protected void page_load(object sender, eventargs e)  
    {  
        createimage(generatecheckcode());  
    }

    private string generatecheckcode()  
    {  
        //生成checkcode  
        int number;  
        char code;  
        string checkcode = string.empty;

        system.random random = new random();

        for (int i = 0; i < 5; i++)  
        {  
            number = random.next();

            if (number % 2 == 0)  
                code = (char)(‘‘0‘‘ + (char)(number % 10));  
            else  
                code = (char)(‘‘a‘‘ + (char)(number % 26));

            checkcode += code.tostring();  
        }

        //response.cookies.add(new httpcookie(“checkcode”, checkcode));  
        session.add(“checkcode”, checkcode);  
        return checkcode;  
    }

    private void createimage(string checkcode)  
    {  
        if (checkcode == null || checkcode.trim() == string.empty)  
            return;  
        int iwidth = (int)(checkcode.length * 15);  
        system.drawing.bitmap image = new system.drawing.bitmap(iwidth, 25);  
        graphics g = graphics.fromimage(image);  
        g.clear(color.white);  
        //定义颜色  
        color[] c = { color.black, color.red, color.darkblue, color.green, color.orange, color.brown, color.darkcyan, color.purple };  
        //定义字体              
        string[] font = {“verdana”,”microsoft sans serif”,”comic sans ms”,”arial”,”宋体”};  
        random rand = new random();  
        //随机输出噪点  
        for (int i = 0; i < 100; i++)  
        {  
            int x = rand.next(image.width);  
            int y = rand.next(image.height);  
            g.drawrectangle(new pen(color.lightgray, 0), x, y, 1, 1);  
        }

//输出不同字体和颜色的验证码字符  
        for (int i = 0; i < checkcode.length; i++)  
        {  
            int cindex = rand.next(7);  
            int findex = rand.next(5);

            font f = new system.drawing.font(font[findex], 10, system.drawing.fontstyle.bold);  
            brush b = new system.drawing.solidbrush(c[cindex]);  
            int ii = 4;  
            if ((i + 1) % 2 == 0)  
            {  
                ii = 2;  
            }  
            g.drawstring(checkcode.substring(i, 1), f, b, 3 + (i * 12), ii);  
        }  
        //画一个边框  
        g.drawrectangle(new pen(color.black, 0), 0, 0, image.width – 1, image.height – 7);

        //输出到浏览器  
        system.io.memorystream ms = new system.io.memorystream();  
        image.save(ms, system.drawing.imaging.imageformat.jpeg);  
        response.clearcontent();  
        response.contenttype = “image/jpeg”;  
        response.binarywrite(ms.toarray());  
        g.dispose();  
        image.dispose();  
    }  
}

admin.aspx 页面代码:

<%@ page language=”c#” autoeventwireup=”true” codefile=”admin.aspx.cs” inherits=”admin” %>  
<!doctype html public “-//w3c//dtd xhtml 1.0 transitional//en” “http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd”>  
<html xmlns=”http://www.w3.org/1999/xhtml” >  
<head runat=”server”>  
    <title>留言本管理-arvan留言本</title>  


    <form id=”form1″ runat=”server”>  
    <div>  
        <asp:multiview id=”multiview1″ runat=”server” activeviewindex=”0″>  
            <asp:view id=”view1″ runat=”server”>  
                <asp:textbox id=”passwdtxt” runat=”server” textmode=”password”></asp:textbox>  
                <asp:requiredfieldvalidator id=”requiredfieldvalidator1″ runat=”server” controltovalidate=”passwdtxt”  
                    display=”dynamic” errormessage=”*请输入密码” setfocusonerror=”true”></asp:requiredfieldvalidator><br />  
                <asp:button id=”loginbtn” runat=”server” onclick=”loginbtn_click” text=”登录” />  
                <asp:label id=”resultlbl” runat=”server”></asp:label></asp:view>  
            <asp:view id=”view2″ runat=”server”>  
                <asp:gridview id=”msggridview” runat=”server” allowpaging=”true” autogeneratecolumns=”false”  
                    datakeynames=”id” datasourceid=”accessdatasource1″ horizontalalign=”center” width=”80%”>  
                    <columns>  
                        <asp:boundfield datafield=”id” headertext=”编号” insertvisible=”false” readonly=”true”  
                            sortexpression=”id”>  
                            <itemstyle horizontalalign=”center” />  
                        </asp:boundfield>  
                        <asp:boundfield datafield=”author” headertext=”作者” sortexpression=”author”>  
                            <itemstyle horizontalalign=”center” />  
                        </asp:boundfield>  
                        <asp:boundfield datafield=”msg” headertext=”留言内容” sortexpression=”msg” />  
                        <asp:boundfield datafield=”date” headertext=”日期” sortexpression=”date”>  
                            <itemstyle horizontalalign=”center” />  
                        </asp:boundfield>  
                        <asp:boundfield datafield=”ip” headertext=”作者ip” sortexpression=”ip”>  
          &  
 nbsp;                 <itemstyle horizontalalign=”center” />  
                        </asp:boundfield>  
                        <asp:commandfield buttontype=”button” showdeletebutton=”true”>  
                            <itemstyle horizontalalign=”center” />  
                        </asp:commandfield>  
                    </columns>  
                </asp:gridview>  
                <asp:accessdatasource id=”accessdatasource1″ runat=”server” conflictdetection=”compareallvalues”  
                    datafile=”~/app_data/guestbook.mdb” deletecommand=”delete from [guestbook] where [id] = ? and [author] = ? and [msg] = ? and [date] = ? and [ip] = ?”  
                    insertcommand=”insert into [guestbook] ([id], [author], [msg], [date], [ip]) values (?, ?, ?, ?, ?)”  
                    oldvaluesparameterformatstring=”original_{0}” selectcommand=”select [id], [author], [msg], [date], [ip] from [guestbook] order by [date] desc”  
                    updatecommand=”update [guestbook] set [author] = ?, [msg] = ?, [date] = ?, [ip] = ? where [id] = ? and [author] = ? and [msg] = ? and [date] = ? and [ip] = ?”>  
                    <deleteparameters>  
                        <asp:parameter name=”original_id” type=”int32″ />  
                        <asp:parameter name=”original_author” type=”string” />  
                        <asp:parameter name=”original_msg” type=”string” />  
                        <asp:parameter name=”original_date” type=”datetime” />  
                        <asp:parameter name=”original_ip” type=”string” />  
                    </deleteparameters>  
                    <updateparameters>  
                        <asp:parameter name=”author” type=”string” />  
                        <asp:parameter name=”msg” type=”string” />  
                        <asp:parameter name=”date” type=”datetime” />  
                        <asp:parameter name=”ip” type=”string” />  
                        <asp:parameter name=”original_id” type=”int32″ />  
                        <asp:parameter name=”original_author” type=”string” />  
                        <asp:parameter name=”original_msg” type=”string” />  
                        <asp:parameter name=”original_date” type=”datetime” />  
                        <asp:parameter name=”original_ip” type=”string” />  
                    </updateparameters>  
                    <insertparameters>  
                        <asp:parameter name=”id” type=”int32″ />  
                        <asp:parameter name=”author” type=”string” />  
                        <asp:parameter name=”msg” type=”string” />  
                        <asp:parameter name=”date” type=”datetime” />  
                        <asp:parameter name=”ip” type=”string” />  
                    </insertparameters>  
                </asp:accessdatasource>  
              &nb  
 sp; <asp:button id=”logoutbtn” runat=”server” text=”退出” onclick=”logoutbtn_click” />   
            </asp:view>  
        </asp:multiview></div>  
    </form>  

admin.aspx 源代码页面

using system;  
using system.data;  
using system.configuration;  
using system.collections;  
using system.web;  
using system.web.security;  
using system.web.ui;  
using system.web.ui.webcontrols;  
using system.web.ui.webcontrols.webparts;  
using system.web.ui.htmlcontrols;</textarea>

public partial class admin : system.web.ui.page  
{  
    protected void page_load(object sender, eventargs e)  
    {

    }  
    protected void loginbtn_click(object sender, eventargs e)  
    {  
        if (passwdtxt.text == “password”)  
        {  
            multiview1.activeviewindex = 1;  
        }  
        else  
        {  
            resultlbl.text = “密码不正确请重试”;  
        }  
    }  
    protected void logoutbtn_click(object sender, eventargs e)  
    {  
        multiview1.activeviewindex = 0;  
    }  
}

css文件代码:

body  
{  
 font-family:宋体 georgia;  
 font-size: 12px;  
 text-align:center;  
}  
#pagediv  
{  
 margin-left:auto;  
 margin-right:auto;  
}  
#msglist  
{  
 margin-left:auto;  
 margin-right:auto;  
}  
#msgdiv  
{  
 background-color: #f8f8ff;  
 border-bottom: #ff6600 1px dashed;  
 border-top: #ff6600 1px dashed;  
}  
#msgcontent  
{  
 font-size: 14px;  
 margin: 10px 10px 10px 10px;  
 padding: 10px 10px 10px 10px;  
 font-family: georgia, 宋体;  
 text-align: left;  
}  
/*结构完成*/  
.author  
{   
 font-size: 14px;   
 text-align: left;  
 font-family: georgia, 宋体;  
 margin-top:5px;  
}  
a, a:link, a:visited, a:active  
{  
 font-size: 14px;  
 text-decoration: none;  
 color: #9400d3;  
}  
a:hover  
{  
 color: #ff6600;  
 border-bottom: #808080 1px dashed;  
}  
img  
{  
 vertical-align: middle;  
 text-align: center;  
}

今天我做了一件错事,将平台的话单下错了,归根结底属于工作疏忽,唉,跟着田姐跑了一早上,把相关部门都跑过来了,结果终于将这件祸事摆平了。在这个单位工作好歹有2年多了,可为什么自己仍然会犯这么低级的错误,我真的很后悔。

不过我觉得话单本身手工干预也是不合适的,是导致出现错误的诱因。唉。出现了错误,没有人会帮你,大家都在看你的笑话,现在的人就这么麻木,这么贱。

这次我的错误也成为了运监的那个女人的口实,以后肯定会拿这说事。我相信。

原本我打算引咎辞职的,连报告都写好了,后来田姐说我们是一个整体,少谁都不行,如果你要走,我也走。朋友也劝我说,犯不上辞职,知错能改就行了,这个时候我多么希望能听到她的鼓励与支持啊。真的。唉。

昨天还是开心的,因为涨薪水了,并且领导给我了一个承诺,可今天就闯祸了,真的大起大落啊。

从现在起,要告诉自己,做事要仔细,象话单做完了一定要核查,不论多么麻烦。如果再出现一次,我真的不能原谅自己,对不起领导对我的栽培。


一 用SqlConnection连接SQL Server

1.加入命名空间

using System.Data.SqlClient;  

2.连接数据库

SqlConnection myConnection = new SqlConnection();  
myConnection.ConnectionString = "user id=sa;password=sinofindb;initial catalog=test;data source=127.0.0.1;Connect Timeout=30";  
myConnection.Open();  

改进(更通用)的方法:

string MySqlConnection="user id=sa;password=sinofindb;Database =test;data source=127.0.0.1;Connect Timeout=30";  
SqlConnection myConnection = new SqlConnection(MySqlConnection);  
myConnection.Open();  

二 用OleDbConnection连接

1.加入命名空间

using System.Data.OleDb;  

2.连接sql server

string MySqlConnection="Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=test;Integrated Security=SSPI;";

SqlConnection myConnection = new SqlConnection(MySqlConnection);  
myConnection.Open();  

3.连接Access(可通过建立.udl文件获得字符串)

string MySqlConnection="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:db2000.mdb;

Persist Security Info=False;  

4.连接Oracle(也可通过OracleConnection连接)

string MySqlConnection="Provider=MSDAORA;Data Source=db; user id=sa;password=sinofindb";  

三.创建Command对象

 
1.SqlCommand 构造函数

①初始化 SqlCommand 类的新实例。

public SqlCommand();  
SqlCommand myCommand = new SqlCommand();  

②初始化具有查询文本的 SqlCommand 类的新实例。

public SqlCommand(string);  
String mySelectQuery = "Select * FROM mindata";  
SqlCommand myCommand = new SqlCommand(mySelectQuery);  

③初始化具有查询文本和 SqlConnection 的SqlCommand类实例。

Public SqlCommand(string, SqlConnection);  
String mySelectQuery = "Select * FROM mindata";  
string myConnectString = "user id=sa;password=;database=test;server=mySQLServer";  
SqlConnection myConnection = new SqlConnection(myConnectString);  
SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);  

④初始化具有查询文本、SqlConnection 和 Transaction 的 SqlCommand 类实例。

public SqlCommand(string, SqlConnection, SqlTransaction);

SqlTransaction myTrans = myConnection.BeginTransaction();  
String mySelectQuery = "Select * FROM mindata";  
string myConnectString = "user id=sa;password=;database=test;server=mySQLServer";  
SqlConnection myConnection = new SqlConnection(myConnectString);  
SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection, myTrans);  

2.建立SqlCommand与SqlConnection的关联。

myCommand.Connection = myConnection;  

或者:

SqlCommand myCommand = myConnection.CreateCommand;  

3.设置SqlCommand的查询文本。

myCommand.CommandText = "Select * FROM mindata";  

或者第2种构造:

SqlCommand myCommand = new SqlCommand(mySelectQuery);  

给SqlCommand对象提供两个查询字符串,每个查询字符串访问不同的表,返回不同的结果集。两个查询语句用分号分隔。

4. 执行命令。

ExecuteReader
 返回一行或多行
 
ExecuteNonQuery
 对 Connection 执行 Transact-SQL 语句并返回受影响的行数(int)
 
ExecuteScalar
 返回单个值(如一个聚合值).返回结果集中第一行的第一列。忽略额外的列或行
 
ExecuteXmlReader
 将 CommandText 发送到 Connection 并生成一个 XmlReader 对象。
 

SqlDataReader myReader = myCommand.ExecuteReader();

或SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

   while(myReader.Read()) //循环读取数据  
   {  
      Console.WriteLine(myReader.GetString(0));// 获取指定列的字符串形式的值  
      Console.WriteLine(myReader. GetValue(1));// 获取以本机格式表示的指定列的值  
    }  
 

CommandText = "select count(*) as NumberOfRegions from region";  
Int count = (int) myCommand.ExecuteScalar();  

关于OleDbCommand对象的使用。

四.DataReader的使用

1.遍历结果集

while (myReader.Read())  
  Console.WriteLine(" {0} {1}", myReader.GetInt32(0), myReader.GetString(1));  
myReader.Close();  

2.使用序数索引器。

while (myReader.Read())  
  Console.WriteLine(" {0} {1}", myReader[0].ToString(), myReader[1].ToString());  
myReader.Close();  

 
3.使用列名索引器。

while (myReader.Read())  
  Console.WriteLine(" {0} {1}", myReader["code].ToString(), myReader["name"].ToString());  
myReader.Close();  

4.使用类型访问器。

public char GetChar(int i); 获取指定列的单个字符串形式的值  
public DateTime GetDateTime(int i); 获取指定列的 DateTime 对象形式的值  
public short GetInt16(int i); 获取指定列的 16 位有符号整数形式的[C#]  
public string GetString(int i); 获取指定列的字符串形式的值  

5.得到列信息。

myReader.FieldCount     获取当前行中的列数  
myReader.GetFieldType(序号)   获取是对象的数据类型的 Type  
myReader.GetDataTypeName(序号)  获取源数据类型的名称  
myReader.GetName(序号)     获取指定列的名称  
myReader.GetOrdinal(序号)   在给定列名称的情况下获取列序号  

6.得到数据表的信息。

myReader.GetSchemaTable()   返回一个 DataTable  

7.操作多个结果集。

myReader.NextResult()     使数据读取器前进到下一个结果集  
do  
{  
  while (myReader.Read())  
  Console.WriteLine(" {0} {1}", myReader.GetInt32(0), myReader.GetString(1));  
}  
while(myReader.NextResult());  

五.DataAdapter

*1.创建SqlDataAdapter *
初始化 SqlDataAdapter 类的新实例。
public SqlDataAdapter();

将指定的 SqlCommand 作为SelectCommand 属性,初始化 SqlDataAdapter 类的新实例。
public SqlDataAdapter(SqlCommand);

用 selectcommand字符串 和 SqlConnection对象初始化SqlDataAdapter 类的新实例。
public SqlDataAdapter(string, SqlConnection);

用 selectcommand字符串 和 一个连接字符串 初始化SqlDataAdapter 类的新实例。
public SqlDataAdapter(string, string);

2.DataAdapter和SqlConnection,SqlCommand建立关联。

1.DataAdapter在构造参数时建立
2.SqlDataAdapter adapter = new SqlDataAdapter();
  adapter.SelectCommand = new SqlCommand(query, conn);

 
3.DataAdapter.Fill()方法。

在 DataSet 中添加或刷新行以匹配使用 DataSet 名称的数据源中的行,并创建一个名为“Table”的 DataTable。
public override int Fill(DataSet);

在 DataSet 中添加或刷新行以匹配使用 DataSet 和 DataTable 名称的数据源中的行。
public int Fill(DataSet, string);

在 DataSet 的指定范围中添加或刷新行以匹配使用 DataSet 和 DataTable 名称的数据源中的行。
public int Fill(DataSet, int, int, string);

在 DataTable 中添加或刷新行以匹配使用 DataTable 名称的数据源中的行。
 public int Fill(DataTable);

 
在 DataTable 中添加或刷新行以匹配使用指定 DataTable 和 IDataReader 名称的数据源中的行。
protected virtual int Fill(DataTable, IDataReader);

在 DataTable 中添加或刷新行以匹配使用 DataTable 名称、指定的 SQL Select 语句和 CommandBehavior 的数据源中的行。
protected virtual int Fill(DataTable, IDbCommand, CommandBehavior);
 
六.DataTable 类

七.DataColumn 类

八.DataRow 类 

九.DataSet 类
1.创建DataSet 对象

初始化 DataSet 类的新实例。
public DataSet();
 
用给定名称初始化 DataSet 类的新实例。
public DataSet(string);
 

2.用DataAdapter填充DataSet

DataSet myds=new DataSet();  
adapter.fill(myds)  
adapter.fill(myds,”表名”);  用一个表去填充DataSet.  

十. DataTableCollection 类

表示 DataSet 的表的集合。

DataTableCollection dtc = ds.Tables;  
DataTable table = dtc[“表名”];  
String strExpr = "id > 5";  
String strSort = "name DESC";  
DataRow[] foundRows = customerTable.Select( strExpr, strSort,);  

进行动态的筛选和排序。
DataTable.Select() 方法 :  获取 DataRow 对象的数组,

①获取所有 DataRow 对象的数组。

public DataRow[] Select();  

②按主键顺序(如没有主键,则按照添加顺序),获取与筛选条件相匹配的所有 DataRow 对象的数组。

public DataRow[] Select(string);  

③获取按照指定的排序顺序且与筛选条件相匹配的所有 DataRow 对象的数组。

public DataRow[] Select(string, string);  

④获取与排序顺序中的筛选器以及指定的状态相匹配的所有 DataRow 对象的数组。

public DataRow[] Select(string, string, DataViewRowState);  

十一。DataView 类

是DataTable内容的动态视图。

1.  创建对象

初始化 DataView 类的新实例。

  public DataView();

用指定的 DataTable 初始化 DataView 类的新实例。

  public DataView(DataTable);

用指定的 DataTable、RowFilter、Sort 和 DataViewRowState 初始化 DataView 类的新实例。

public DataView(DataTable, string, string, DataViewRowState);

DataView myview = new DataView(ds.Tables["Suppliers"], "id > 5", "name DESC",  
DataViewRowState.CurrentRows);  

2* .得到DataView的行数据。*

   foreach (DataRowView myrowview in myview)  
   {  
     for (int i = 0; i < myview.Table.Columns.Count; i++)  
        Console.Write(myrowview [i] + " ");  
     Console.WriteLine();  
   }

上周五把我自己写的一个简单的留言本给一个搞开发的朋友看,结果发现了2个严重的bug,一个是登录Bug,一个是Sql注入漏洞.

说实话,在进行写留言本的时候,我根本就不知道SQL注入漏洞是怎么样的,后来朋友给我讲了原理,做了示范,我发现要写出安全的代码真的需要注意很多问题。朋友给我的建议是:
第一条就是使用OleDBParameters,即参数,不要使用拼凑的SQL语句(动态SQL语句),而是使用参数,将变量给参数。
第二条就是控制用户输入,即任何时候不信任用户的输入,这个需要正则表达式来完成。
第三条,过滤HTML文本,即使用HttpUtility.HTMLEncode()或者Server.HTMLEcode()

下面的这些关于参数的代码,可能比较笨拙,但是很管用。因为oledb不像SQL Server那样,SQL SERVER使用命名参数,而OLEDB使用的是定位参数,即需要参数的地方使用‘?’。

下面是我写的一段代码:

    public static string filename = “~//App_Data//test.mdb”;  
    public static string ConnString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + HttpContext.Current.Server.MapPath(filename);//定义连接字符串

OleDbConnection conn = new OleDbConnection(ConnString); //实例化一个oledbconnection对象  
        OleDbDataAdapter oleda = new OleDbDataAdapter();//实例化一个DataAdapter对象  
        DataSet ds = new DataSet();//实例化一个数据集  
        string insertSql = ” insert into [test] (name,email,weburl,Content,ip) VALUES (?,?,?,?,?)”;//定义需要执行的sql语句,注意问号  
        OleDbCommand olecmd = new OleDbCommand(insertSql, conn);//实例化一个oledbcommand对象,以sql语句和conn对象作为参数传递给构造函数

        olecmd.Parameters.Add(“@name”, OleDbType.Variant).Value = HttpUtility.HtmlEncode(nameTxt.Text);  
        olecmd.Parameters.Add(“@email”, OleDbType.Variant).Value = HttpUtility.HtmlEncode(emailTxt.Text);  
        olecmd.Parameters.Add(“@weburl”, OleDbType.Variant).Value = HttpUtility.HtmlEncode(weburlTxt.Text);  
        olecmd.Parameters.Add(“@Content”, OleDbType.Variant).Value = HttpUtility.HtmlEncode(ContentTxt.Text);  
        olecmd.Parameters.Add(“@ip”, OleDbType.Variant).Value = Session[“IP”].ToString();  
//上面5条开始添加SQL语句中的参数,注意顺序。  
        oleda.InsertCommand = olecmd;//将olecmd对象赋值给InsertCommand属性  
        conn.Open();//打开数据库  
        oleda.InsertCommand.ExecuteNonQuery();//执行命令。  
      conn.Close();//关闭数据库

注意:如果在编译的时候,得到错误“至少有一个参数没有被指定值”,请将@符号去掉。即olecmd.Parameters.Add(“Content”, OleDbType.Variant).Value = HttpUtility.HtmlEncode(ContentTxt.Text);。这个问题让我困扰了3个小时。

大家注意到了吧,参数的数据类型,我全部选择的是OleDbType.Variant,它映射到.net框架的object类型。我没有注意到什么ntext之类的数据类型。

以上代码主要是将参数用户DataAdapter,如果大家有更方便,更安全的方法,也请告诉我。谢谢。

关于其他的详细信息,比如SQL的,oracle的,大家可以看看MSDN。

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/WD_ADONET/html/f21e6aba-b76d-46ad-a83e-2ad8e0af1e12.htm

我写的留言本程序的地址是 http://et.bestzhou.org/


/// <summary>

/// 自动给邮件地址或email地址加上url  

using System;

using System.Text.RegularExpressions;

namespace CommLayer

{

/// <summary>

/// 自动给邮件地址或email地址加上url

/// </summary>

public class HyperlinkUrl

{

private static Regex urlregex = new Regex(@"(http://([w.]+/?)S*)",

RegexOptions.IgnoreCase|RegexOptions.Compiled);

private static Regex emailregex = new Regex(@"([a-zA-Z_0-9.-]+@[a-zA-Z_0-9.-]+.w+)",

RegexOptions.IgnoreCase|RegexOptions.Compiled);

public HyperlinkUrl()

{

}

/// <summary>

/// 生成带连接的字符串

/// </summary>

/// <param name="link">需要生成带连接地址的字符串</param>

/// <returns>经过转换的字符串</returns>

public static string GenHyperlinkUrl(string link)

{

link = emailregex.Replace(link, "<a href=mailto:$1>$1</a>");

link = urlregex.Replace(link, "<a href="$1" target="_blank">$1</a>");

return link;

}

}

}