0

作为我正在整理的项目的一部分,我有一个 Arduino 通过 C♯ 更新 MySQL 数据库,并且在另一个位置我有另一个 C♯ 程序对数据库执行简单的 SELECT 查询,并通过将其发现传达给另一个 Arduino串行。我已经为第二个程序编写了大部分代码,但最后遇到了一些烦人的问题。

下面是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Xml;
using System.IO.Ports;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string hkday;
            string hkall;
            //SERIAL
            SerialPort serialPort1 = new SerialPort();
            serialPort1.PortName = "COM4";
            serialPort1.BaudRate = 9600;
            serialPort1.NewLine = "\n";

            //OPEN SERIAL
            serialPort1.Open();

            //SQL
            string connString = "Server=xxxx;Uid=xxxx;Password=xxxx;Port=xxxx;Database=xxxx;";
            MySqlConnection conn = new MySqlConnection(connString);
            MySqlCommand command1 = conn.CreateCommand();
            command1.CommandText = "Select USERS from HK where UPTIME='HKDAY'";
            MySqlCommand command2 = conn.CreateCommand();
            command2.CommandText = "Select USERS from HK where UPTIME='HKALL'";

            //EXECUTE QUERIES
            if (_continue = true)
            {
                conn.Open(); //Connect
                MySqlDataReader reader1 = command1.ExecuteReader();
                while (reader1.Read())
                {
                    //Write to value and string   
                    Console.WriteLine(reader1["USERS"].ToString());
                    hkday = reader1["USERS"].ToString();
                }

                Console.ReadLine();
                _continue = false;
                conn.Close(); //Disconnect
            }
            else
            {
                conn.Open(); //Connect
                MySqlDataReader reader2 = command1.ExecuteReader();
                while (reader2.Read())
                {
                    //Write to console and string    
                    Console.WriteLine(reader2["USERS"].ToString());
                }
                hkall = reader2["USERS"].ToString();

                Console.ReadLine();
                _continue = true;
                conn.Close(); //Disconnect

                //WRITE STRINGS TO SERIAL
                serialPort1.WriteLine(
                    String.Format(hkday, hkall));
            }

            serialPort1.Close();

        }

        public static bool _continue { get; set; }
    }
}
  1. 我无法弄清楚我的标题为 WRITE STRINGS TO SERIAL 的部分需要如何编写语法并将其放置在代码中才能引用“hkday”和“hkall”

  2. 我的 'if (_continue = true)' 标志似乎不起作用,我不知道为什么。

  3. 我认为如果解决了这两个问题,程序应该可以工作,你还能看到其他明显的问题吗?

谢谢,我知道这些只是小问题,但我似乎无法解决它们。

潜在重要:我正在尝试将输出设为 '123,456\n',因为我的 arduino 程序已经将其识别为它的输入。


更新

收到我的答案后,我将这个项目与我目前正在做的另一个项目结合起来,尝试让 arduino 通过 C# 更新 MySQL 数据库,然后让它下载它没有更新的表数据以显示通过另一个arduino。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using MySql.Data.MySqlClient;

namespace SQL_Scraper
{

    public partial class Sandro : Form
    {
        //Serial Settings
        SerialPort UNO = new SerialPort("COM4", 9600);
        SerialPort MEGA = new SerialPort("COM3", 9600);

        //Incoming Data String
        string RxString;

        //Int for download
        int? vnday = 0;
        int? vnall = 0;

        public Sandro()
        {
            InitializeComponent();

            //Open UNO port
            UNO.Open();

            //Open MEGA Port
            MEGA.Open();
        }

        private void MEGA_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

        }

        private void Sandro_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (UNO.IsOpen | MEGA.IsOpen)
            {
                UNO.Close();
                MEGA.Close();
            }
        }

        private void DisplayText(object sender, EventArgs e)
        {

        }

        private void Begin_Click(object sender, EventArgs e)
        {
            //Turn off start button
            Begin.Enabled = false;
            //?
            this.Invoke(new EventHandler(DisplayText));
            //Create Event Handler if data is receiverd
            MEGA.DataReceived += new SerialDataReceivedEventHandler(MEGA_DataReceived);

            string SQLString = "Server=benchmarkcount.db.9506323.hostedresource.com;Uid=benchmarkcount;Password=Watercress2428;Port=3306;Database=benchmarkcount;";
            MySqlConnection SQLConnection = new MySqlConnection(SQLString);

            //Receive data
            RxString = MEGA.ReadExisting();

            //Append Serial Input to Output box)
            outputBox.AppendText(RxString);

            //Get Unsaved input from text box
            string input = outputBox.Text;
            string[] inputLines = input.Split('\n');

            //Upload findings from MEGA to SQL
            foreach (string line in inputLines)
            {
                if (line.EndsWith("\r")) //Makes sure line is complete
                {
                    if (line.StartsWith("Today's total users: "))
                    {
                        string dayUsers = line.Substring(20).Trim();
                        MySqlCommand UpdateHKDAY = SQLConnection.CreateCommand();
                        UpdateHKDAY.Parameters.AddWithValue("param1", dayUsers);
                        UpdateHKDAY.CommandText = "UPDATE HK SET USERS=?param1 WHERE UPTIME='HKDAY'";
                        SQLConnection.Open();
                        UpdateHKDAY.ExecuteNonQuery();
                        SQLConnection.Close();
                    }
                    else if (line.StartsWith("All-time total users: "))
                    {
                        string allUsers = line.Substring(21).Trim();
                        MySqlCommand UpdateHKALL = SQLConnection.CreateCommand();
                        UpdateHKALL.Parameters.AddWithValue("param2", allUsers);
                        UpdateHKALL.CommandText = "UPDATE HK SET USERS=?param2 WHERE UPTIME='HKALL'";
                        SQLConnection.Open();
                        UpdateHKALL.ExecuteNonQuery();
                        SQLConnection.Close();
                    }
                }
            }

            //Only keep unparsed text in text box
            outputBox.Text = inputLines[inputLines.Length - 1];

            //Download Numbers Query
            MySqlCommand DownUsers = new MySqlCommand("Select USERS, UPTIME from VN where UPTIME IN ('VNDAY', 'VNALL')", SQLConnection);

            //Open Connection
            SQLConnection.Open();

            //Execute Downloading Numbers
            MySqlDataReader theResults = DownUsers.ExecuteReader();
            while (theResults.Read())
            {
                switch (theResults["UPTIME"] as string)
                {
                    case "VNDAY":
                        vnday = theResults["USERS"] as int?;
                        break;
                    case "VNALL":
                        vnall = theResults["USERS"] as int?;
                        break;
                }
            }

            //Do things with the results
            UNO.WriteLine(String.Format("{0},{1}", vnday, vnall));
            Console.WriteLine(String.Format("{0},{1}", vnday, vnall));

            //Close Connection
            SQLConnection.Close();
        }

        private void Sandro_Load(object sender, EventArgs e)
        {

        }

        private void Cease_Click(object sender, EventArgs e)
        {
            Begin.Enabled = true;
            Cease.Enabled = false;
        }
    }
}

但是,我希望能够在我的 inputBox 中检查这些数据——发送到 arduino 的数据,以确保它的格式为“vnday,vnall\n”

4

2 回答 2

1

你的问题和例子有太多的矛盾。您似乎认为单独的应用程序运行之间存在静态持久性。没有。每次运行都会清除所有静态变量。如果您有一个在同一个应用程序域内循环调用的方法,情况会有所不同。

此外,根据您的变量名称和输出要求,USERS 字段是一个数字。

因此,假设您有下表:

USERS    UPTIME
------   ------
123456   HKALL
234567   HKDAY

以下代码:

public static void Main()
{
    int? hkday = 0;
    int? hkall = 0;

    using (MySqlConnection conn = new MySqlConnection("..."))
    {
        conn.Open();

        MySqlCommand cmd = new MySqlCommand("Select USERS, UPTIME from HK where UPTIME IN ('HKDAY', 'HKALL')", conn);

        MySqlDataReader reader = cmd.ExecuteReader();

        //this assumes that there is only one record per 'HKDAY' and 'HKALL',
        //otherwise the last value will be stored
        while (reader.Read())
        {
            switch (reader["UPTIME"] as string)
            {
                case "HKDAY":
                    hkday = reader["USERS"] as int?;
                    break;
                case "HKALL":
                    hkall = reader["USERS"] as int?;
                    break;
            }
        }
    }

    Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}

将输出:

234,567
123,456

或者,如果您希望运行独立查询:

private static int? GetUSERS(string hkval)
{
    using (MySqlConnection conn = new MySqlConnection("..."))
    {
        conn.Open();

        MySqlCommand cmd = new MySqlCommand("Select USERS from HK where UPTIME=@hkval", conn);
        cmd.Parameters.AddWithValue("hkval", hkval);

        MySqlDataReader reader = cmd.ExecuteReader();

        if (reader.Read())
            return reader["USERS"] as int?;

        return null;
    }
}

public static void Main()
{
    int hkday = (int)GetUSERS("HKDAY");
    int hkall = (int)GetUSERS("HKALL");

    Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}

您还可以使用 args 将 HKDAY/HKALL 作为参数传递给您的应用程序。

于 2012-07-23T20:33:26.133 回答
0

我不是 C 程序员,但知道很多串口,我想这解决了你的第一个问题。

//WRITE STRINGS TO SERIAL
      serialPort1.Write(hkday);             // do not append line feed
      serialPort1.WriteLine(hkall);         // append line feed
于 2012-07-20T17:32:50.063 回答