【问题标题】:How to store values of select query in variables in the webservice?如何将选择查询的值存储在 Web 服务的变量中?
【发布时间】:2012-06-04 16:48:17
【问题描述】:

我是 Web 服务开发的新手。我使用 c# 和 mysql 在 asp.net 中制作了 webservice。

我想将选择查询的值存储在变量中,然后我想将其插入表中。

我使用了以下代码:

//for inserting new game details in the tbl_Game by FB
    [WebMethod]
    public string InsertNewGameDetailsForFB(string gametype, string player1, string player2, string player3, string player4, string player5)
    {
        string success = "Error in Insertion";

        string selectID = "Select UserID from tbl_userinfo where Facebook_ID IN ('" + player1 + "','" + player2 + "','" + player3 + "')";
        con = new MySqlConnection(conString);
        con.Open();
        MySqlCommand cmd = new MySqlCommand(selectID, con);
        MySqlDataReader ids = cmd.ExecuteReader();
        string id1="", id2="", id3="";
        while (ids.Read())
        {
           id1 = ids.GetString(0);
           id2 = ids.GetString(1);
           id3 = ids.GetString(2);

        }

        string insertNewGame = "Insert into tbl_game(Type,Player1,Player2,Player3,Player4,Player5) values";
        insertNewGame += "( '" + gametype + "' , '" + id1 + "', '" + id2 + "','" + id3 + "', '" + player3 + "','" + player4 + "', '" + player5 + "' )";
        con = new MySqlConnection(conString);
        con.Open();
        MySqlCommand cmd1 = new MySqlCommand(insertNewGame, con);
        int success1 = cmd1.ExecuteNonQuery();
        con.Close();

        string gameID = "Select MAX(GameID) from tbl_game";
        con = new MySqlConnection(conString);
        con.Open();
        MySqlCommand cmd2 = new MySqlCommand(gameID, con);
        string gameid = cmd2.ExecuteScalar().ToString();

        if (success1 > 0)
        {
           success="Inserted Successfully, GameID is - " + gameid;
        }
        return success;
    }

我该怎么做?

谢谢。

【问题讨论】:

    标签: c# asp.net mysql web-services


    【解决方案1】:

    您的第一个问题是您如何尝试从第一个查询中读取 UserID。此查询不会返回三列,而是返回三行。所以你需要做这样的事情:

    int index = 0;
    while (ids.Read())
    {
        switch (index)
        {
            case 0:
                id1 = ids.GetString(0);
                break;
            case 1:
                id2 = ids.GetString(0);
                break;
            case 2:
                id3 = ids.GetString(0);
                break;
        }
        index += 1;
    }
    

    这应该正确存储它们。我的第二个建议是,既然这是一个 Web 服务,你应该避免 SQL 注入攻击并使用参数化查询而不是动态 SQL。您可以使用网络上的大量示例。

    我的最终建议是对实现 IDisposable 的对象(即连接对象、命令、阅读器等)虔诚地使用 using 语句。这可确保正确清理对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多