c#winform更新mysql数据库

时间:2014-03-14 07:28:09

标签: c# mysql winforms

我这里有一个代码,每月统计打印页数:

public  void OnDataReceived(IAsyncResult asyn)
    {
        try
        {

            CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;//creating object of the class

            //end receive of data
            int iReceive  = 0 ;
            iReceive = theSockId.thisSocket.EndReceive (asyn);
            char[] chars = new char[iReceive +  1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); //creating object for decoding
            int charLen = d.GetChars(theSockId.dataBuffer, 0, iReceive, chars, 0);
            System.String szData = new System.String(chars);
            string test = count_page.Text + szData;
            string count_pages = Regex.Replace(test, "[^.0-9]", "");
            count_page.Text = count_pages;
            dbConnect.Update(count_pages); //problem lines
            //as data arrives the bytes are appended to the existing string printer throws data in an ASCII format 1 byte at a time

            WaitForData();
        }
        catch (ObjectDisposedException )
        {
            System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
        }
        catch(SocketException se)
        {
            MessageBox.Show (se.Message ); //gives an error message if any exception has occured
        }
    }  

如果我不把我评论的行放在上面的问题行中,这段代码可以正常工作:

dbConnect.Update(count_pages);  

enter image description here

但是我希望它在数据库中更新,所以我将计数页面的值传递给类dbConnect.Update。但是,当我添加这一行。 count_pages的值似乎不再显示在文本框中,并且它也没有将值传递给数据库无法更新的dbConnect.Update类。有谁有任何想法为什么这个haoppen?

1 个答案:

答案 0 :(得分:1)

我建议您使用Trace.WriteLine(count_pages);而不是消息框,因为消息框会停止您的方法。

别忘了添加using System.Diagnostics;

您可以在output窗口中看到结果,您可以在Visual Studio顶级菜单的view中看到它。

添加:

关于您的新问题,请检查http://msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx 并做出类似的东西

private static void ReceiveCallback( IAsyncResult ar ) {
    try {
        // Retrieve the state object and the client socket 
        // from the asynchronous state object.
        StateObject state = (StateObject) ar.AsyncState;
        Socket client = state.workSocket;
        // Read data from the remote device.
        int bytesRead = client.EndReceive(ar);
        if (bytesRead > 0) {
            // There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
                //  Get the rest of the data.
            client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                new AsyncCallback(ReceiveCallback), state);
        } else {
            // All the data has arrived; put it in response.
            if (state.sb.Length > 1) {
                response = state.sb.ToString();
            }
            // Signal that all bytes have been received.
            receiveDone.Set();
        }
    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}