简体   繁体   中英

How to insert wifi scan data into SQL Server table

I have scanned wifi data in C# that I have split into required form MAC, SSID and RSSi. When I push a button, the results should be inserted into a SQL Server table that I already created. And if I push the button again, it stops inserting. I have tried several methods and could not get it to work, Will appreciate assist

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

namespace WICED_SERIALPORT_TEST
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       private void button1_Click(object sender, EventArgs e)
       {
           string[] ports = SerialPort.GetPortNames();

           foreach (string port in ports)
           {
               comboBox1.Items.Add(port);
           }
       }

       string t;

       private void button2_Click(object sender, EventArgs e)
       {
           t = comboBox1.Text.ToString();
           sErial(t);
       }

       SerialPort sp;

       void sErial(string Port_name)
       {
           sp = new SerialPort(Port_name, 115200, Parity.None,8, 
     StopBits.One);    
           sp.DataReceived += new 
           SerialDataReceivedEventHandler(DataReceivedHandler);
           sp.Open();
       }

       private void DataReceivedHandler(object sender, 

       SerialDataReceivedEventArgs e)
       {
           SerialPort sp = (SerialPort)sender;
           string msg = string.Empty;
           bool canCont = false;

           while (!canCont)
           {
               msg += sp.ReadLine();

               if (msg.Contains("Scan complete "))
               {
                   canCont = true;
               }
           }

           //string w = sp.ReadLine();
           //string w = sp.ReadExisting();

           // string msg = sp.ReadExisting();

           string[] msgArr = msg.Split('\r');

           Invoke(new Action(() => listBox1.Items.Clear()));

           List<string[]> list = new List<string[]>();
           List<Networks> Scan = new List<Networks>();

           for (int i = 0; i < msgArr.Length; i++)
           {
               list.Add(msgArr[i].Split(new string[] { "  " }, 
   StringSplitOptions.RemoveEmptyEntries));
           }

           for (int i = 0; i < list.Count; i++)
           {
               if (i > 2)
               {
                   if (list[i].Length > 4)
                   {
                        int numOfSplits = 0;
                        List<string> tempList = new List<string>();

                        for (int ii = 0; ii < list[i].Length; ii++)
                        {
                            if (numOfSplits < 6)
                            {
string[] temp1 = list[i][ii].Split(new char[] { ' ' },  
StringSplitOptions.RemoveEmptyEntries);
                                numOfSplits += temp1.Length;

                                for (int iii = 0; iii < temp1.Length; iii++)
                                {
                                    tempList.Add(temp1[iii]);
                                }
                            }
                            else
                            {
                                tempList.Add(list[i][ii]);
                            }
                        }

                        Scan.Add(new Networks()
                        {
                            ID = Convert.ToInt32(tempList[0]),
                            NetworkType = tempList[1],
                            MAC = tempList[2],
                            RSSi = Convert.ToInt32(tempList[3]),
                            Rate = Convert.ToDouble(tempList[4]),
                            Channel = Convert.ToInt32(tempList[5]),
                            Security = tempList[6],
                            SSID = tempList[7],
                        });
                    }
               }
          }

          if (msg != String.Empty)
          {
              Invoke(new Action(() => richTextBox1.AppendText(msg)));
          }

          for (int i = 0; i < Scan.Count; i++)
          {
             Invoke(new Action(() => listBox1.Items.Add(Scan[i].MAC)));
             Invoke(new Action(() => listBox2.Items.Add(Scan[i].RSSi)));
             Invoke(new Action(() => listBox3.Items.Add(Scan[i].SSID)));

             msg = string.Empty;
             list.Clear();
          }
      }

    public SqlConnection con = new SqlConnection(@"Data Source=    
(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\AP_SCAN_DATA.mdf;
 Integrated Security=True");

    private void button3_Click(object sender, EventArgs e)
    {
        using (SqlConnection connection = new SqlConnection(@"Data  Source=
(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\AP_SCAN_DATA.mdf;   
Integrated Security=True"))
        {
           using (SqlCommand command = new SqlCommand())
           {
               command.Connection = connection;            // <== lacking
               command.CommandType = CommandType.Text;
               command.CommandText = "INSERT into LOCATIONSCAN ((Scan[i].SSID), (Scan[i].MAC),(Scan[i].RSSi)) VALUES (@SSID, @MAC, @RSSi)";

               command.Parameters.AddWithValue("@SSID", listBox1);
               command.Parameters.AddWithValue("@MAC", listBox2);
               command.Parameters.AddWithValue("@RSSi",listBox3);

               try
               {
                   connection.Open();
                   int recordsAffected = command.ExecuteNonQuery();
               }
               catch(SqlException)
               {
                   // error here
               }
               finally
               {
                   connection.Close();
               }
           }
       }
    }
 }

Firstly, you have an empty CATCH block that will cause your SqlExceptions to disappear silently. Remove the CATCH and the exception will help you. Secondly, your CommandText looks odd, without knowing your database schema I would guess it should be something like this;

command.CommandText = "INSERT into LOCATIONSCAN (SSID, MAC, RSSi) VALUES ('@SSID', '@MAC', '@RSSi')";

Next issue is that you have to specify the property of the listbox that holds the value when adding the parameter. For example it might be the SelectedValue property.

command.Parameters.AddWithValue("@SSID", listBox1.SelectedValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM