1

我正在将一条记录添加到远程 mysql 数据库中,然后我想检查它是否已添加 - 所以我想尝试选择这个特定的记录。

我的代码:

    public void Select(string filename)
    {
        string query = "SELECT * FROM banners WHERE file = '"+filename+"'";

        //open connection
        if (this.OpenConnection() == true)
        {
            //create command and assign the query and connection from the constructor
            MySqlCommand cmd = new MySqlCommand(query, connection);

            //Execute command
            cmd.ExecuteNonQuery();

            //close connection
            this.CloseConnection();
        }
    }

如何检查服务器的响应?还是选定的记录?它是 c# windows 窗体应用程序。

4

3 回答 3

2

您可以扩展您的插入语句,而不是进行另一个往返(带有额外的选择)

SELECT LAST_INSERT_ID();

执行你的插入命令

command.ExecureQuery();

并获取最后插入记录的 ID。

看看MySQL 信息函数

于 2012-07-18T23:51:43.143 回答
1

试试这个:

public void Select(string filename)
{
        string query = "SELECT * FROM banners WHERE file = '"+filename+"'";

        //open connection
        if (this.OpenConnection() == true)
        {
                //create command and assign the query and connection from the constructor
                MySqlCommand cmd = new MySqlCommand(query, connection);

                //Get the DataReader from the comment using ExecuteReader
                            MySqlDataReader reader = cmd.ExecuteReader(); 
                while (myReader.Read())  
                { 
                    //Use GetString etc depending on the column datatypes.
                    Console.WriteLine(myReader.GetInt32(0)); 
                } 

                //close connection
                this.CloseConnection();
        }
}

检查此 URL 了解更多信息: http: //msdn.microsoft.com/en-us/library/haa3afyz (v=vs.100).aspx

于 2012-07-18T23:42:45.220 回答
0

您可以在运行command.ExecuteNonQuery()forINSERT语句本身时执行此操作。command.ExecuteNonQuery()返回受影响的行数(在您的情况下插入)。所以

if(command.ExecuteNonQuery()>0)
{
 //inserted
}
else
{
 //Not inserted
}

http://dev.mysql.com/doc/refman/5.1/en/connector-net-ref-mysqlclient.html#connector-net-ref-mysqlclient-mysqlcommand-executenonquery

于 2012-07-19T04:57:40.953 回答