如何将串行数据流保存到sql数据库

时间:2014-09-07 00:53:48

标签: c# sql sql-server 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

希望有人可以提供帮助

2 个答案:

答案 0 :(得分:6)

query1是一个字符串。它包含SQL。您忘记在该字符串中执行SQL。您需要创建SqlCommand并执行它。

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

暂且不说:

您应该在数据库中使用数字类型存储数字数据,否则查询您的数据将是一个巨大的PITA。

您的数据似乎走上了一条非常奇怪的道路。首先,将其复制到UI。然后将其从UI复制到数据库。为什么不将数据一次复制到UI,一次复制到数据库?

您在UI线程上以紧密循环方式更新UI。这不会更新您的UI,因为您的UI线程在循环中忙碌。

答案 1 :(得分:1)

您应该将此代码提交给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数据类型。这将占用DB中较少的空间。

并且不要将timeStamp数据类型用于您的时间戳。 TimeStamp数据类型是欺骗性的,使用dateTime并将其默认值设置为getDate()(因此程序不需要做额外的工作)

它甚至可能会被折旧http://technet.microsoft.com/en-us/library/aa260631(v=sql.80).aspx