注册 登录
编程论坛 ASP.NET技术论坛

[求助]数据连接的错误

xiaobin2012 发布于 2007-06-20 17:34, 510 次点击

protected void Button1_Click(object sender, EventArgs e)
{
this.SqlDataSource1.Insert();
string filepath = "", filename = "", mfilename, mfilepath;
if(""!=FileUpload1.PostedFile.FileName)
{
filepath = FileUpload1.PostedFile.FileName;
filename = filepath.Substring(filepath.LastIndexOf(".") + 1);
try
{
mfilepath = Server.MapPath("ima/");
mfilename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
string strsql = "insert into userinfo(imagepath)values('" + mfilepath + "')";
con = new SqlConnection(strCon);
con.Open();
SqlCommand cmd = new SqlCommand(strsql, con);
cmd.ExecuteNonQuery();
con.Close();//这句怎么不执行????

}
catch { Response.Write("<scrip>alert('上传文件不存在')</scrip>"); }
}

7 回复
#2
川流不息2007-06-20 18:08
cmd.ExecuteNonQuery();
你是不是這句出錯,然後直接跳到catch中去了?那樣是不會執行下面的close方法的。
#3
yichen2007-06-20 18:21
再加个finally
#4
川流不息2007-06-20 18:22
con.Close();//这句怎么不执行????
那就把這句放在finally裡面吧。
#5
xiaobin20122007-06-20 18:34
回复:(川流不息)con.Close();//这句怎么不执行??...
   finally 没用过 ^_^!
#6
xiaobin20122007-06-20 18:52
this.SqlDataSource1.Insert();这句是不是会跟另外的操作数据库有冲突阿?
错误提示是
不能将值 NULL 插入列 'username',表 'E:\会员注册\APP_DATA\DATABASE.MDF.dbo.userinfo';列不允许有空值。INSERT 失败。语句已终止


#7
xiaobin20122007-06-20 19:52
问题已解决,都不是上两位所说的问题,还是谢谢两位了

this.SqlDataSource1.Insert();这是插入一条数据,原来的下面是插入一条数据
只要把原来的插入改为更新就可以了


string filepath = "", filename = "", mfilename, mfilepath;
if ("" != FileUpload1.PostedFile.FileName)
{
filepath = FileUpload1.PostedFile.FileName;
filename = filepath.Substring(filepath.LastIndexOf(".") + 1);

try
{
mfilepath = Server.MapPath("ima/");
mfilename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
string strsql = "update userinfo set imagepath='ima\\"+mfilename+"'where username='"+TextBox1.Text+"'" ;
con = new SqlConnection(strCon);
con.Open();
SqlCommand cmd = new SqlCommand(strsql, con);
cmd.ExecuteNonQuery();


con.Close();


}

#8
川流不息2007-06-21 09:14
错误提示是
不能将值 NULL 插入列 'username',表 'E:\会员注册\APP_DATA\DATABASE.MDF.dbo.userinfo';列不允许有空值。INSERT 失败。语句已终止。
不是你改update的問題,是你以前的insert語句insert into userinfo(imagepath)values('" + mfilepath + "')";
的問題。說你的列'username'不能為空,也就是說你這個字段設置不能為空,那麼就要在插入語句裡面加入這個字段:
insert into userinfo(username,imagepath)values('yourname','" + mfilepath + "')";

而且,你把你的insert改成update難道不會對你的操作造成不同的影響嗎?

1