我有一个显示用户帖子的网页,并允许用户添加新帖子。我使用SqlDataSource
来从数据库中提取数据,并且我已经绑定了一个转发器以显示检索到的帖子。我的问题是当用户想要插入新帖子时。这是我正在遵循的逻辑:
1-获取用户在帖子区域输入的数据,如文本和图像(用户可以在帖子中上传图像)。
2-使用从新帖子区域获得的值构建插入查询。
3-执行查询。
4-使用SqlDataSource
更新DataBind()
。
5-使用DataBind()
更新与数据源关联的转发器。
由于某种原因,insert命令插入不起作用。我尝试过使用典型的SqlConnection方法,带参数查询的SqlConnection方法(我使用参数而不是直接使用插入的帖子信息,例如@text),我甚至尝试使用数据源本身执行插入,没有任何效果。这是我的代码:
protected void submitPost(object sender, EventArgs e)
{
if (uploadImageBtn.HasFile) //check if a file was uploaded by the user.
{
//step 1: save at the server:
uploadImageBtn.SaveAs(Server.MapPath("~/uploadedImages/") + uploadImageBtn.FileName); //working :)
String fileName = uploadImageBtn.FileName; //get the uploaded file name to store it in the database.
//get current date and time to insert them in DB:
DateTime dateValue = Convert.ToDateTime (DateTime.Now.Date.ToString("dd/MM/yyy"));
DateTime timeValue = Convert.ToDateTime ( DateTime.Now.ToString("hh:mm:ss"));
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open(); //open db
string query2 = "insert into posts_tbl (postDate, postTime, postText, postVideo2, PostImage2, pUserName, boundPost) VALUES (@date,@time,@post,@video,@img,@userName,@boundPost)";
SqlCommand command = new SqlCommand(query2, con); //build a command
command.Parameters.AddWithValue("@date", dateValue);
command.Parameters.AddWithValue("@time", timeValue);
command.Parameters.AddWithValue("@post", post_txt.Text);
command.Parameters.AddWithValue("@video", "NULL");
command.Parameters.AddWithValue("@img", fileName);
command.Parameters.AddWithValue("@userName", "name");
command.Parameters.AddWithValue("@boundPost", "NULL");
int returned= command.ExecuteNonQuery(); //returns null
con.Close();
postsSource.DataBind();
postsRepeater.DataBind();
}//end if
}//end method
以下是我使用数据源本身编写的代码:
postsSource.InsertCommandType= SqlDataSourceCommandType.Text;
postsSource.InsertCommand = "insert into posts_tbl (postDate, postTime, postText, postVideo2, PostImage2, pUserName, boundPost) VALUES (@date,@time,@post,@video,@img,@userName,@boundPost)";
postsSource.InsertParameters.Add("date", dateValue);
postsSource.InsertParameters.Add("time", timeValue);
postsSource.InsertParameters.Add("post", post_txt.Text.ToString());
postsSource.InsertParameters.Add("video", "Null");
postsSource.InsertParameters.Add("img", fileName);
postsSource.InsertParameters.Add("userName", "name");
postsSource.InsertParameters.Add("boundPost", "NULL");
postsSource.Insert();
postsSource.DataBind();
postsRepeater.DataBind();
但是,最后一种方法不允许为参数指定非字符串值(例如dateValue和timeValue,它们必须是Datetime)。
任何人都可以告诉我导致插入错误的原因是什么?而且,我是否正确更新数据源和转发器?
感谢。
答案 0 :(得分:1)
在与 Steve 和 Andrei 讨论代码后,我发现了我的问题。
我在一个需要int数据类型的字段中插入一个空值。我刚从插入查询中删除了该字段,一切正常。
全部谢谢。