关于ExecuteNonQuery()不能将数据插入数据库
发表在ASP.NET图书答疑
2015-03-31
是否精华
是
否
版块置顶:
是
否
public int sqlEx(string cmdstr)
{
OleDbConnection conn = Getcon(); //连接数据库
conn.Open();
System.Web.HttpContext.Current.Response.Write(conn.State);
OleDbCommand cmd = new OleDbCommand(cmdstr,conn);
try
{
cmd.ExecuteNonQuery();
return 1;
}
catch (Exception e)
{
return 0;
}
finally
{
conn.Dispose();
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
int reValue = CheckName();
if (reValue == -1)
{
Response.Write("<script>alert('用户名存在!');</script>");
}
else
{
DB db = new DB();
string UserName = this.txtUserName.Text;
string PassWord = this.txtPwd.Text;
string Email = this.txtEmail.Text;
string cmdstr = "insert into tb_User(UserName,PassWord,Email) values('" + UserName + "','" + PassWord + "','" + Email + "')";
try
{
reValue = db.sqlEx(cmdstr);
if (reValue == 1)
{
Response.Write("<script>alert('注册成功!');</script>");
}
else if(reValue==0)
{
Response.Write("<script>alert('注册失败1!');</script>");
}
}
catch(Exception ee)
{
Response.Write("<script>alert('注册失败!');</script>");
}
}
}
在执行过程中,System.Web.HttpContext.Current.Response.Write(conn.State);能够输出open,说明数据库已经打开并建立连接。但是在sqlEx函数调用的过程执行cmd.ExecuteNonQuery()时,只会返回0不能将数据插入数据库中,我的数据库是access。
{
OleDbConnection conn = Getcon(); //连接数据库
conn.Open();
System.Web.HttpContext.Current.Response.Write(conn.State);
OleDbCommand cmd = new OleDbCommand(cmdstr,conn);
try
{
cmd.ExecuteNonQuery();
return 1;
}
catch (Exception e)
{
return 0;
}
finally
{
conn.Dispose();
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
int reValue = CheckName();
if (reValue == -1)
{
Response.Write("<script>alert('用户名存在!');</script>");
}
else
{
DB db = new DB();
string UserName = this.txtUserName.Text;
string PassWord = this.txtPwd.Text;
string Email = this.txtEmail.Text;
string cmdstr = "insert into tb_User(UserName,PassWord,Email) values('" + UserName + "','" + PassWord + "','" + Email + "')";
try
{
reValue = db.sqlEx(cmdstr);
if (reValue == 1)
{
Response.Write("<script>alert('注册成功!');</script>");
}
else if(reValue==0)
{
Response.Write("<script>alert('注册失败1!');</script>");
}
}
catch(Exception ee)
{
Response.Write("<script>alert('注册失败!');</script>");
}
}
}
在执行过程中,System.Web.HttpContext.Current.Response.Write(conn.State);能够输出open,说明数据库已经打开并建立连接。但是在sqlEx函数调用的过程执行cmd.ExecuteNonQuery()时,只会返回0不能将数据插入数据库中,我的数据库是access。