简体   繁体   中英

data not being written to local SQL Server database file

I have written that gets data from a sensor, I am trying to write this data to a local SQL Server database file.

Code doesn't produce any errors but the data is not being written to the data table.

I have used the following code: (any suggestions?)

    static void Insert(string date, double value, string deviceName)
    {
        string path = Directory.GetCurrentDirectory();
        string filename = path + "\\Database1.mdf";
        Console.WriteLine(filename);
        string connectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=" + filename + ";Database=Database1";

        using (SqlConnection conn = new SqlConnection(connectionString))

        try
        {
            {
                conn.Open();
                SqlDataAdapter adapter = new SqlDataAdapter();
                using (SqlCommand cmd = new SqlCommand("INSERT INTO DataTable VALUES(@Id, @Date, @Value, @Device Name)", conn))
                {
                    num11 += 1;
                    cmd.Parameters.AddWithValue("@Id", num11);
                    cmd.Parameters.AddWithValue("@Date", date);
                    cmd.Parameters.AddWithValue("@Value", value);
                    cmd.Parameters.AddWithValue("@Device Name", deviceName);

                    cmd.ExecuteNonQueryAsync();
                    //rows number of record got inserted
                }
                conn.Close();
            }
        }
        catch (SqlException es)
        {
            Console.WriteLine(es);
            //Display Error message
        }
    }

You're calling ExecuteNonQueryAsync to asynchronously insert the record - but you're then closing the connection immediately, while the insert has almost certainly not yet completed.

You should either use the synchronous call instead, or use asynchrony properly - probably making the method asynchronous, and awaiting the result of ExecuteNonQueryAsync . You need to wait for the operation to complete before you close the connection, basically.

You don't need to call Close explicitly at all, by the way - you've already got a using statement, so the connection will be disposed as execution exits the block. (It's not clear why you've got an extra block inside the using statement either, by the way.)

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