配置数据库文件
连接数据库方法
法一
protected void Page_Load(object sender, EventArgs e)
{
/关联web.config文件 wjy为数据库别名/
string constr1 = ConfigurationManager.ConnectionStrings["wjy"].ToString();
MySqlConnection conne = new MySqlConnection(constr1);
conne.Open();
/数据库 查询语句/
string sql = "select * from student";
MySqlDataAdapter da = new MySqlDataAdapter(sql,conne);
/数据/
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
conne.Close();
}
法二
static string constr = ConfigurationManager.ConnectionStrings["wjy"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
/实例化MySqlConnection对象/
MySqlConnection conn = new MySqlConnection(constr);
conn.Open();
string selstr = "select * from student";
MySqlCommand cmd = new MySqlCommand(selstr, conn);
/*实例化MySqlDataReader对象 cmd.ExecuteReader()*/
/*数据*/
MySqlDataReader dr = cmd.ExecuteReader();
/*gtridview 数据绑定 释放资源*/
GridView1.DataSource = dr;
GridView1.DataBind();
conn.Close();
}
法三
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["wjy"].ToString();
MySqlConnection conn = new MySqlConnection(constr);
conn.Open();
string sql2 = "select * from student";
MySqlDataAdapter da2 = new MySqlDataAdapter();
da2.SelectCommand = new MySqlCommand(sql2, conn);
DataSet ds = new DataSet();
da2.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
}
数据库增删改 方法三种
法一
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text.Trim();
string name = TextBox2.Text.Trim();
string sex = DropDownList1.Text;
string department = DropDownList2.Text;
string constr = ConfigurationManager.ConnectionStrings["xby"].ToString();
MySqlConnection conn = new MySqlConnection(constr);
conn.Open();
string selstr = "select * from student";
MySqlDataAdapter da = new MySqlDataAdapter(selstr, conn);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow mr = dt.NewRow();
mr[0] = id;
mr[1] = name;
mr[2] = sex;
mr[3] = department;
dt.Rows.Add(mr);
da.Update(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
conn.Close();
}
法二
protected void Button2_Click(object sender, EventArgs e)
{
string id = TextBox3.Text.Trim();
string tname = TextBox4.Text.Trim();
string tclass = TextBox5.Text.Trim();
string constr1 = ConfigurationManager.ConnectionStrings["xby"].ToString();
MySqlConnection conn1 = new MySqlConnection(constr1);
conn1.Open();
string selstr1 = "select * from teacher";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = new MySqlCommand(selstr1, conn1);
MySqlCommandBuilder builder = new MySqlCommandBuilder(da1);
DataSet ds = new DataSet();
da1.Fill(ds);
DataRow NewRow = ds.Tables[0].NewRow();
NewRow[0] = id;
NewRow[1] = tname;
NewRow[2] = tclass;
ds.Tables[0].Rows.Add(NewRow);
da1.Update(ds);
Response.Write("
原文:https://www.cnblogs.com/wang-jingyuan/p/14815269.html