简体   繁体   中英

Issues inserting into sql database from asp.net

I have a lot more columns than what I have here for you, but I'm just trying to get to post the primary key column TrackingID (nchar[10]) as a test - if I can get that to work, I can get the rest of them to work. I have a windows forms application that makes a similar query and runs perfectly, so seeing as how it's both C# I'm having a hard time understanding what's going wrong. Is it the connection string or the sql query? The table name is Full. There are 23 columns total, but the only primary key is Tracking ID which cannot be null. In all instances, these queries are a OnClick button event. As you will be able to see I have tried several routes. I am hoping to set this up to be parameterized to prevent SQL Injections. The first bit of code you will see is from a Windows Forms Application in C# that (while is vulnerable) works consistently. Below, you will see the asp.net code.

    private void licensesubmitbutton_Click(object sender, EventArgs e)
    {
        try
        {
            System.Data.SqlClient.SqlConnection sqlConnection1 =
    new System.Data.SqlClient.SqlConnection("Data Source=data99;Initial Catalog=LicenseInventoryMgr;Integrated Security=True;Connect Timeout=0;Trusted_Connection=Yes");

            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = "INSERT LIMTable (Software,Host,AssetTag,ActivationDate,LicenseNumber) VALUES ('" + softwarecombobox.Text + "','" + hostnamebox.Text + "','" + assettagcombobox.Text + "','" + dateactivateddatetimepicker.Value.ToString("yyyy-MM-dd") + "','" + licensekeytextbox.Text + "')";
            cmd.Connection = sqlConnection1;

            sqlConnection1.Open();
            cmd.ExecuteNonQuery();
            sqlConnection1.Close();
            MessageBox.Show("Successfully Submitted!");
        }
        catch (System.Exception )
        {
            MessageBox.Show("Submission unsuccessful. Try saving and refreshing first!");
        }
    }

And here is the ASP.NET code I've tried.

    protected void submit_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(@"Data Source=data99;Initial Catalog=LFM_Archive;Integrated Security=True");
            string sql = "INSERT INTO Full (TrackingID) values (@TrackingID)";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@TrackingID", SqlDbType.NChar);
            cmd.Parameters["@TrackingID"].Value = 6789;
            cmd.ExecuteNonQuery();
            conn.Close();

            MailMessage m1 = new MailMessage("y@x.net", "x@x.net");
            m1.Subject = "SQL Query Success";
            m1.Body = "SQL Query Success :)";
            m1.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "mailserver99";
            smtp.EnableSsl = false;
            //System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            //NetworkCred.UserName = "username";
            //NetworkCred.Password = "password";
            smtp.UseDefaultCredentials = true;
            //smtp.Credentials = NetworkCred;
            smtp.Port = 25;
            smtp.Send(m1);

        }
        catch
        {
            MailMessage m2 = new MailMessage("y@x.net", "x@x.net");
            m2.Subject = "SQL Query Failed";
            m2.Body = "SQL Query Failed :(";
            m2.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "mailserver99";
            smtp.EnableSsl = false;
            smtp.UseDefaultCredentials = true;
            smtp.Port = 25;
            smtp.Send(m2);
        }
    }

The end result displays query success or failure in the form window that this pulls from, and/or sends an email. When I no longer have to test it, the emails will be simple notifications that the form has been posted to the archive. Commented code in the asp.net application only means that I tried it and when it didn't work, I commented it and tried a new method.

It was suggested I try and put in a exception message to see better - that helps some. The submitsuccess.Text is where the messages will come up. Here's the results: "Incorrect syntax near the keyword 'Full'."

That makes it sound like it's the query. "Full" is the table name in the DB.

ANSWERED Here's what worked:

            SqlConnection conn = new SqlConnection(@"Data Source=data99;Initial Catalog=LFM_Archive;Integrated Security=True");
            string sql = "INSERT INTO [Full] (TrackingID) values (@TrackingID)";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@TrackingID", SqlDbType.NChar, 10);
            cmd.Parameters["@TrackingID"].Value = empfirst.Text;
            cmd.ExecuteNonQuery();
            conn.Close();

The problem is that FULL is a reserved word in SQL. See this Technet link.

To solve your problem, use brackets on reserved keywords like so:

string sql = "INSERT INTO [Full] (TrackingID) values (@TrackingID)";

TRY USING THIS CODE

INSERT INTO [Full] (TrackingID) values ('@TrackingID')

Issue is due to FULL is keyword

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