所以我有一个表,我想从表中选择一个值并将其存储到C#变量中。

我现在所拥有的是

String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
try
{
    conn.Open();
    queryStr = "";
    queryStr = "SELECT ipaddress from robolinks where roboID=?roboID";

    cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
    cmd.Parameters.AddWithValue("?roboID", roboID);
    cmd.ExecuteReader();
    conn.Close();

//after closing the connection, get the ipaddress and key it into web browser.

}
catch(Exception)
{

}


所以我知道我已经选择了它,但是如何在C#中操作ipaddress?

感谢您的协助!

最佳答案

首先,如果使用ExecuteReader,则需要首先获取值,然后才需要关闭连接。
其次是ExecuteReader返回SqlDataReader,因此,如果要从Sql中获取某些值,则需要将ExecuteReader的返回变量分配给某个值

SqlDataReader dr = cmd.ExecuteReader();


现在,使用手动(https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx)开始编码:

string roboIp;
// Because you know that id is int so imho you don't need parameters.
queryStr = "SELECT ipaddress from robolinks where roboID="+roboID+";";
// This is right.
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
conn.Open();
var dr = cmd.ExecuteReader();
// Now check if any rows returned.
if (dr.HasRows)
{
    dr.Read();// Get first record.
    roboIp = dr.GetString(0);// Get value of first column as string.
}
dr.Close();// Close reader.
conn.Close();// Close connection.


但是,如果仅选择一个值,则最好使用ExecuteScalar而不是ExecuteReader

string roboIp;
queryStr = "SELECT ipaddress from robolinks where roboID="+roboID+";";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
conn.Open();
var queryResult = cmd.ExecuteScalar();//Return an object so first check for null
if(queryResult!=null)
    // If we have result, then convert it from object to string.
    roboIp = Convert.ToString(queryResult);
else
    // Else make id = "" so you can later check it.
    roboIp = "";

10-08 05:09