一、在Microsoft Visual Studio 里建立网站起名为SQLTest:

vs4

vs5

二、insertSQL.aspx设计界面如下,其中用户名后TextBox控件命名为txtUserName,

         密码后TextBox控件ID 改为txtPwd。

vs6

三、双击Button按钮进入insertSQL.aspx.cs。完整代码及详细注释如下

//本例采用ADO.NET连接数据库
using System;
using System.Configuration;
using System.Data;//ADO.NET结构的类包含在System.Data命名空间中
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;//该命名空间包含访问SQL Server数据库的类

public partial class _Default : System.Web.UI.Page
{

protected void Button1_Click(object sender, EventArgs e)
{
//连接数据库
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Persist Security Info = True; User id=sa; pwd=sa; database=dbSQLTest; server=(local)\\SQLExpress";
//使用SqlConnection类的ConnectionString属性获取或设置用于打开SQL Server数据库的字符串
//Security当为false时,将在连接中指定用户ID和密码,为true时将使用当前的windows账户凭据进行身份验证
//id、pwd分别为登录数据库的登录名和密码。database后跟数据库名称。另外要注意server=(local)若你的数据库登录时没有\SQLExpress便可不加
conn.Open();

//得到SqlCommand对象
SqlCommand comm = new SqlCommand();
comm.Connection = conn;//使用SqlCommand类的Connection方法获取或设置SqlCommand的此实例使用的SqlConnection

//使用插入一行数据,完成非查询的SQL操作
comm.CommandText = "INSERT INTO users(Uname,Upwd) VALUES('" + txtUserName.Text.Trim() + "','" + txtPwd.Text.Trim() + "')";
//使用SqlCommand类的CommandText属性获取或设置要对数据源执行的Transact-SQL语句或存储过程
//后面内容为基本的SQL语句,其中txtUserName、txtPwd分别为设计窗体文本框的名字

//调用SqlCommand的ExecuteNonQuery方法执行SQL语句
comm.ExecuteNonQuery();//ExecuteNonQuery方法只能执行非查询的(非select)Transact-SQL语句并可返回受影响的行数.查询命令(select)参见下面selectSQL程序

//断开连接
conn.Close();
}

}

三、运行并输入界面:

vs7

四、插入成功:

vs4

【声明:潘协灿原创,转载请注明出处! 潘协灿博客 www.panxiecan.cn】

arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()