新建空web项目
新建首页
index.asps 添加代码
index.aspx.cs 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
static string strConn = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection conn = new SqlConnection(strConn);
protected void Page_Load(object sender, EventArgs e)
{
LoadInfo();
}
private void LoadInfo()
{
ConnectDB();
string strSql = @"select DeptName from E_Dept";
DataTable dt = ExecuteQuery(strSql);
rpt_test.DataSource = dt;
rpt_test.DataBind();
CloseDB();
}
protected void btn_test_Click(object sender,EventArgs e)
{
ConnectDB();
string strSql = @"insert into E_Dept (DeptName) values ('" + txt_test.Text + "')";
ExecuteNonQuery(strSql);
LoadInfo();
CloseDB();
}
public void ConnectDB()
{
try
{
conn = new SqlConnection(strConn);
conn.Open();
}
catch (Exception ex)
{
}
}
public void CloseDB()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
public DataTable ExecuteQuery(string sqlString)
{
try
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, conn);//从数据库中查询
da.Fill(ds);//将数据填充到DataSet
return ds.Tables[0];
}
catch (Exception ex)
{
return null;
}
}
public int ExecuteNonQuery(string sqlString)
{
try
{
SqlCommand cmd = new SqlCommand(sqlString, conn);
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
return -1;
}
}
}数据库创建表E_Dept
Web.config 配置数据库连接
运行