执行读者没有回应

时间:2012-06-11 08:22:31

标签: c# c#-4.0

我有一个PHP代码。这是代码,我要把它翻译成.NET但在某些方面我遇到了麻烦。

function processInput($conn, $MessageArray, $mobilenumber, $date, $odd)
{

$strSQLUSER="SELECT * FROM tbl_tiduser WHERE username='".addslashes($MessageArray[0])."' AND stat!='1' AND stat!='4'";

$result_user=odbc_exec($conn,$strSQLUSER) or die("Could not connect to database");

这是转换后的.NET代码

public class ProcessInput
{   
    private string msg_arr;
    private string MooseSeenInput(string MobileNo,string Date,string odd,params Array[] msg_arr)
    {


 SqlCommand com = new SqlCommand("SELECT * FROM tbl_tiduser WHERE username=@username AND stat!='1' AND stat!='4'", mycon);
                    com.Parameters.AddWithValue("@username",username);
                    using (SqlDataReader reader = com.ExecuteReader())

     // whats the next part need to come here ???

}

这是不完整的。我不打算编译....

3 个答案:

答案 0 :(得分:3)

private static void ReadOrderData(string connectionString)
{
    string queryString =
        "SELECT OrderID, CustomerID FROM dbo.Orders;";

    using (SqlConnection connection =
               new SqlConnection(connectionString))
    {
        SqlCommand command =
            new SqlCommand(queryString, connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        // Call Read before accessing data.
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }

        // Call Close when done reading.
        reader.Close();
    }
}

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

答案 1 :(得分:1)

我会使用类似的东西来获取您之后的列:

string username = null;
using (SqlDataReader reader = com.ExecuteReader()) {
    if (reader.read()) {
        username = (string)reader["mydbcolumnname"];
    }
    reader.Close();
}

请注意,如果您想要提取所有结果行(而不是单步执行),那么您通常会使用 SqlDataAdapter 来填充 DataSet (而不是读者),例如:

string username;
using (SqlDataAdapter adapter = new SqlDataAdapter(com))
{
    using (DataSet ds) 
    {
        adapter.Fill(ds);
        username = (string)ds.Tables[0].Rows[0]["mycolumnname"];
    }
}

答案 2 :(得分:1)

我一切都很轻松;我会写一个class来反映我正在阅读的记录,即

public class User {
    public int Id {get;set;}
    public string Name {get;set;}
}

并使用"dapper"

var user = myCon.Query<User>(
  "SELECT * FROM tbl_tiduser WHERE username=@username AND stat not in ('1','4')",
  new {username}).SingleOrDefault();

if(user == null) { /* not found, presumably throw an exception */ }

string name = user.Name; // etc

然后你不需要搞乱命令,读者,参数等(看看如何干净地将username变成db参数?)。