簡體   English   中英

如何將串行數據流保存到sql數據庫

[英]how to save serial data stream to sql database

我在存儲來自arduino防風罩的數據時遇到問題。 我正在將數據作為數組並將其轉換為字符串,但是我的問題是存儲它,我再次檢查了與ms sql的連接,並且工作正常。我認為問題出在timeStamp中,但我不知道如何解決它

這是主要代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using weathertest.Serial;
using System.Configuration;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Timers;




namespace weathertest 
{

    public partial class Form1 : Form
    {

        serialmanager _spManager;
        public Form1()
        {
            InitializeComponent();

            UserInitialization();
            _spManager.StartListening();
        }

        private void UserInitialization()
        {
            _spManager = new serialmanager();
            serialconfig mySerialSettings = _spManager.CurrentSerialSettings;
            serialSettingsBindingSource.DataSource = mySerialSettings;


            _spManager.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
        }



        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _spManager.Dispose();
        }
        public static String GetTimestamp(DateTime value) {
            return value.ToString("dd-MM-yyyy HH:mm:ss");//yyyyMMddHHmmssffff
        }
        void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
        {
            if (this.InvokeRequired)
            {
                // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
                this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e });
                return;
            }

            int maxTextLength = 1000; // maximum text length in text box
            if (tbData.TextLength > maxTextLength)
                tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength);

            // This application is connected to a GPS sending ASCCI characters, so data is converted to text
            string str = e.Data;
            tbData.AppendText(str);
            tbData.ScrollToCaret();
            string strValue = str;
            string[] strArray = strValue.Split(' ');

            try
            {

                foreach (object obj in strArray)
                {
                    string constring = "Data Source=BASHKIM;Initial Catalog=Weather;Integrated Security=True";
                    SqlConnection conn = new SqlConnection(constring);
                    conn.Open();
                    String timeStamp = GetTimestamp(DateTime.Now);

                    label1.Text =  (strArray[0]);
                    label2.Text =  (strArray[1]);
                    label3.Text =  (strArray[2]);
                    label4.Text =  (strArray[3]);
                    label5.Text =  (strArray[4]);
                    label6.Text =  (strArray[5]);
                    label7.Text =  (strArray[6]);
                    label8.Text =  (strArray[7]);
                    label9.Text =  (strArray[8]);
                    label10.Text = (strArray[9]);
                    label11.Text = (strArray[10]);
                    label12.Text = (strArray[11]);
                    label13.Text = (strArray[12]);
                    label14.Text = (strArray[13]);
                    label15.Text = (strArray[14]);
                    label16.Text = timeStamp;




                    string query1 = @"INSERT INTO daily (winddir,windspeedmph,windgustdir,windspdmph_avg2m,windgustdir_10m,winddir_avg2m,humidity,tempf,rainin,dailyrainin,pressure,batt_lvl,light_lvl,timeStamp) values ("
      + label1.Text + "," + label2.Text + "," + label3.Text + "," + label4.Text + "," + label5.Text + "," + label6.Text + "," + label7.Text + "," + label8.Text + "," + label9.Text + "," + label10.Text + "," + label11.Text + "," + label12.Text + "," + label3.Text + "," + label14.Text + "," + label16.Text + ")";
                    conn.Close();
                }
                    richD.AppendText(str);
                    richD.ScrollToCaret();


            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message); 
            }



        }


        private void button1_Click(object sender, EventArgs e)
        {
            _spManager.StartListening();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'weatherDataSet2.daily' table. You can move, or remove it, as needed.
            //this.dailyTableAdapter.Fill(this.weatherDataSet2.daily);
            // TODO: This line of code loads data into the 'weatherDataSet.daily' table. You can move, or remove it, as needed.
          //  this.dailyTableAdapter.Fill(this.weatherDataSet.daily);


        }
    }
}

這是我的數據庫:

Databasefoto

希望有人能提供幫助

query1是一個字符串。 它包含SQL。 您忘記在該字符串中執行SQL。 您需要創建一個SqlCommand並執行它。

using(var cmd = new SqlCommand(query1, conn))
{
    cmd.ExecuteNonQuery();
}

作為旁白:

您應該在數據庫中使用數字類型存儲數字數據,否則查詢數據將是一個龐大的PITA。

您的數據似乎走了一條非常奇怪的道路。 首先,將其復制到UI。 然后將其從UI復制到數據庫。 為什么不將數據一次復制到UI,一次復制到數據庫?

您正在緊緊地在UI線程上更新UI。 這不會更新您的UI,因為您的UI線程忙於循環。

您應該將此代碼提交到http://codereview.stackexchange.com 您可以使此代碼更有效。 以下是您可以創建SqlCommand的方法示例。 無需關閉您的sql連接,using語句會處理它。

        using (conn)
        {
            conn.Open();
            SqlDataAdapter query = new SqlDataAdapter();
            query.InsertCommand = new SqlCommand("INSERT INTO daily (winddir,windspeedmph,windgustdir,windspdmph_avg2m,windgustdir_10m,winddir_avg2m,humidity,tempf,rainin,dailyrainin,pressure,batt_lvl,light_lvl,timeStamp) values "+
                                                                   "(@winddir,@windspeedmph,@windgustdir,@windspdmph_avg2m,@windgustdir_10m,@winddir_avg2m,@humidity,@tempf,@rainin,@dailyrainin,@pressure,@batt_lvl,@light_lvl,@timeStamp)",conn);

            query.InsertCommand.Parameters.Add("@winddir", SqlDbType.NChar).Value = (strArray[0]);
            query.InsertCommand.Parameters.Add("@windspeedmph", SqlDbType.NChar).Value = (strArray[1]); 


            query.InsertCommand.ExecuteNonQuery();
        }

由於nvarchar是可變長度,因此嘗試使用nvarchar而不是nchar作為SQL數據類型。 這將減少數據庫中的空間。

並且不要將timeStamp數據類型用於您的時間戳。 TimeStamp數據類型具有欺騙性,請使用dateTime並將其默認值設置為getDate()(這樣,程序就不必做額外的工作)

它甚至可能會貶值http://technet.microsoft.com/zh-cn/library/aa260631(v=sql.80).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM