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 ???

}

这是不完整的。我不会编译它....

4

3 回答 3

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

于 2012-06-11T08:25:18.773 回答
1

我很容易;我会写一个class反映我正在阅读的记录的,即

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

并使用“精致”

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 参数的?)。

于 2012-06-11T08:38:27.953 回答
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"];
    }
}
于 2012-06-11T08:27:02.070 回答