【问题标题】:Insert SQL (Access) not working using webmethods Asp.net使用 webmethods Asp.net 插入 SQL (Access) 不起作用
【发布时间】:2013-04-19 05:50:16
【问题描述】:

我正在尝试使用 webmethod(services) 和网站将一些字段插入本地 ms 访问数据库。我试过抬头,但似乎无法发现我哪里出错了。谁能告诉我我是否做得对。下面的代码不会将新数据添加到数据库中,也不会将我引导回请求的页面。

服务网络方法:

[WebMethod]
public void AddNewPosts(string postUserName, string postTitle, DateTime postMessagepostDateTime, int subTopicId, string postMessage)
{
    //Connection string for the datbase
    string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Forum.accdb;Persist Security Info=True";
    OleDbConnection myConn = new OleDbConnection(database);

    //Execute the query
    string queryStr = "Insert into Posts (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "'," + postMessagepostDateTime + ")";

    // Create a command object 
    OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
    // Open the connection 
    myCommand.Connection.Open();
    myCommand.ExecuteNonQuery();
    myCommand.Connection.Close();
}

从我的网站调用上述方法:

 protected void btnSubmit_Click(object sender, EventArgs e)
{
    //string postUserName = Page.User.Identity.Name;
    string postUserName = "tom123";
    string postTitle = txtTitle.Text;
    string postMessage = txtMessage.Text;
    DateTime postDateTime = DateTime.Now;
    int subTopicId = int.Parse(Request.QueryString["id"]);

    Service fs = new Service();
    fs.AddNewPosts(postUserName, postTitle, postDateTime, subTopicId, postMessage);

    //Redirect back to the SubTopic page
    Response.Redirect("SubTopic.aspx?id=" + subTopicId.ToString());


}

【问题讨论】:

  • 你是说没有错误信息吗?在不了解更多信息的情况下,请确保您尝试插入的 id 尚未在您的表中。
  • 您还应该看到 ExecuteNonQuery() 的返回值是什么: int returnVal = myCommand.ExecuteNonQuery();
  • @Constanta 我传递的 ID 可以多次使用,这决定了帖子需要插入哪个主题。帖子 ID 是唯一的,不会影响该列。是的,根本没有错误消息。单击按钮时它什么也不做

标签: asp.net database web-services insert webmethod


【解决方案1】:

您可以尝试在日期时间前后加上引号吗 string queryStr = "插入帖子 (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "','" + postMessagepostDateTime + "')";

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多