首页 > 解决方案 > updating sql server database using c# in asp.net

问题描述

There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?

protected void Page_Load(object sender, EventArgs e) {
    rno.Text = Request.QueryString["rno"];//rno is a textbox


    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "select fname from table1 where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read()) {
        fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
    }
    reader.Close();
    command.Dispose();
    cnn.Close();

    fName.ReadOnly = true;
}

protected void modify_Click(object sender, EventArgs e) {

    fName.ReadOnly = false;
}

protected void savechanges_Click(object sender, EventArgs e) {
    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();


    String sql = "update table1 set fname=@fname where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@fname", sfname);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());

    command.ExecuteNonQuery();
    command.Dispose();
    cnn.Close();
    fName.ReadOnly = true;
}

标签: c#asp.netsql-server

解决方案


我已经尝试过您的代码,该代码也执行得很好并且更新了数据库表。

我试过如下:

        string connectionString = @"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
        SqlConnection cnn = new SqlConnection(connectionString);
        cnn.Open();


        String sql = "update TestTable set fname=@fname where rno =rno";

        SqlCommand command = new SqlCommand(sql, cnn);
        command.Parameters.AddWithValue("@fname", "Test");
        command.Parameters.AddWithValue("@rno", "rno");

        command.ExecuteNonQuery();
        command.Dispose();
        cnn.Close();

我尝试过的另一种方法。

            using (SqlConnection connection = new SqlConnection(connectionString ))
                    {
                        connection.Open();
                        var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";

                        using (SqlCommand cmd = new SqlCommand(queryText, connection))
                        {
                            responseResults = await cmd.ExecuteNonQueryAsync();
                        }
                        connection.Close();

                    }

希望它会有所帮助


推荐阅读