简体   繁体   中英

SQL multiple statements, INSERT not working

I am developing a web app and have encountered a problem. I need to insert username and ip address into a SQL database table "log" when someone tries (successfully or unsuccessfully) to login. ID, time and date are inserted automatically... For some reason I am unable to get it working in my login form. INSERT statement works ok if I initiate it from another form, but I can't get it working together with the SELECT statement I use for checking login credentials.

I have tried different solutions, but none of them inserts data into the table... It does not throw an error, it just doesn't insert a new row into "log" table.

Any help is appreciated. :)

protected void btnLog_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString()))
    {
        string username = null;
        string password = null;
        string ipAddress = null;

        SymCryptography cryptic = new SymCryptography();
        SqlCommand cmdSelect = new SqlCommand();
        SqlCommand cmdLog = new SqlCommand();
        SqlDataReader myReader = null;

        cmdSelect.Connection = conn;
        cmdLog.Connection = conn;

        cmdSelect.CommandText = "SELECT * FROM uporabniki WHERE up_ime=@up_ime AND geslo=@geslo";
        cmdSelect.CommandType = CommandType.Text;
        cmdLog.CommandText = "INSERT INTO log (up_ime, ip) VALUES (@up_ime, @ip)";
        cmdLog.CommandType = CommandType.Text;

        cmdSelect.Parameters.Add("@up_ime", SqlDbType.NVarChar, 20).Value = tbUsr.Text;
        cmdSelect.Parameters.Add("@geslo", SqlDbType.NVarChar, 20).Value = cryptic.Encrypt(tbPwd.Text);
        cmdLog.Parameters.Add("@up_ime", SqlDbType.NVarChar, 20).Value = tbUsr.Text;
        cmdLog.Parameters.Add("@ip", SqlDbType.NVarChar, 20).Value = ipAddress;

        conn.Open();
        try
        {
            //cmdLog.ExecuteNonQuery();  I tried it here, but it doesn't work
            myReader = cmdSelect.ExecuteReader();
            if (myReader.Read())
            {
                username = myReader["up_ime"].ToString();
                password = myReader["geslo"].ToString();
                Session["rights"] = myReader["pravice"];
                Session["login"] = "OK";
                pravice = true;
            }
            myReader.Close();
            //cmdLog.ExecuteNonQuery();  I tried it here, but it doesn't work
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        conn.Close();
    }
    //I tried to open connection again, but stil INSERT does not work
    /* using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString()))
    {
        string ipAddress = null;
        SqlCommand cmdLog = new SqlCommand();
        cmdLog.Connection = conn;
        cmdLog.CommandText = "INSERT INTO log (up_ime, ip) VALUES (@up_ime, @ip)";
        cmdLog.CommandType = CommandType.Text;
        cmdLog.Parameters.Add("@up_ime", SqlDbType.NVarChar, 20).Value = tbUsr.Text;
        cmdLog.Parameters.Add("@ip", SqlDbType.NVarChar, 20).Value = ipAddress;
        conn.Open();
        try
        {
            cmdLog.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        conn.Close();
    }

    if (pravice == true)
    {
        Response.Redirect("Default.aspx");
    }
    else
    {
        Response.Redirect("Login.aspx");
    }*/ 
}

Your not executing your cmdLog.ExecuteNonQuery(); statement.

Also, try opening a query window in your sql database and run the following against it.

INSERT INTO log (up_ime, ip) VALUES (<some time>, <test ip text>)

If the error lies in sql server you should be returned an error message stating if the problem lies withing SQL Server.

Also try changing:

    cmdLog.Parameters.Add("@up_ime", SqlDbType.NVarChar, 20).Value = tbUsr.Text;
    cmdLog.Parameters.Add("@ip", SqlDbType.NVarChar, 20).Value = ipAddress;

To:

  cmdLog.Parameters.Add("@up_ime", tbUsr.Text);
  cmdLog.Parameters.Add("@ip",  ipAddress);

Check whether your connection string value is ok. Also put a break point on the:

   conn.Open();

See whether you get an error? If not then that means your connectionstring is ok.

Uncomment this line after Try{}

 //cmdLog.ExecuteNonQuery();  I tried it here, but it doesn't work

and put a break point on it .. see whether you get an error?

Also from your code I can see that you are inserting a null ipaddress value into the table. See whether the column in your database is allowed to accept nulls??

The using statement will clean up the connection in the garbage collection process which happens at an indeterminable time. This is why 1 of the orders of execution you've tried doesn't work (the connection may not be usable). Suggest you do either:

  1. Both operations within 1 using (connection), make sure you close the connection in a finally() block and re-init your command against the newly opeend connection.

  2. Have 2 different connections conn1 and conn2 and perform the separate operations in each.

EDIT: I have re-read and you say no errors occur? - try checking the result of ExecuteNonQuery (it returns an integer to show the number of rows that have been affected - if this is zero there is a problem with your insert statement).

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