如何更改数据库中列的值

时间:2018-03-22 02:28:49

标签: c# asp.net localdb

我在Lucky Draw系统的注册页面上工作。我创建了一个包含emp_id,emp_name,emp_deparment和attendance的数据库Employees。我已将列出勤率设置为默认值" Absent"。但是数据库显示为null。单击此链接可查看 employees database

因此,注册过程是用户需要使用USB条形码扫描器扫描条形码,然后系统将显示其名称并将出勤列中的默认值更新为“#34;存在"。”我坚持使用该部分。任何人都可以给我一些想法/解决方案。

出勤代码:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Attendance : System.Web.UI.Page
{
    SqlCommand cmd = new SqlCommand();
    SqlConnection con = new SqlConnection();
    string str;
    protected void Page_Load(object sender, EventArgs e)
    {
        con.ConnectionString = @"Data Source= (LocalDB)\MSSQLLocalDB; AttachDbFilename = 
           C:\Users\Nor  Asyraf  Mohd No\source\repos\LuckyDraw\LuckyDraw\App_Data\ticket.mdf; 
            Integrated Security = True";

        con.Open();
        txtText.Focus();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {



    }

void idcheck()
        {
            string selectQuery = "SELECT count(*) FROM EMPLOYEES where EMP_ID = '" + txtText.Text + "'";
            SqlCommand cmd = new SqlCommand(selectQuery, con);
            SqlDataReader myReader = null;
            int count = Convert.ToInt32(cmd.ExecuteScalar());
            if (count > 0)

            {
                myReader = cmd.ExecuteReader();
                while (myReader.Read())
                    lblError.Text = myReader["EMP_NAME"].ToString();
                lblError.ForeColor = System.Drawing.Color.Green;

            }
            else
            {
                lblError.Text = "Employee not available";
                lblError.ForeColor = System.Drawing.Color.Red;
            }

        }

}

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你想在btnSave_Click函数中更新Attandence的值为'Present'。我认为你应该能够使用以下代码来做到这一点:

protected void btnSave_Click(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionString)) {
        using (SqlCommand command = connection.CreateCommand()) {
            command.Text = "UPDATE EMPLOYEES SET Attendance = 'Present' WHERE EMP_ID = @id";
            command.Parameters.AddWithValue("@id", txtText.Text);
            connection.Open();

            command.ExecuteNonQuery();

            connection.Close();
        }
    }
}

使用command.Parameters.AddWithValue的好处是它有助于防止SqlInjections。

using语句确保在代码离开using块后处理连接。您可能也希望在其他函数中使用它们,如果不这样做,可能是上面的代码抛出异常,因为您有多个并发连接到同一个数据库。

答案 1 :(得分:0)

您的问题不明确,但为了设置列的默认值,请转到SQL Management Studio并执行以下操作:

  1. 右键单击表格
  2. 选择设计
  3. 选择所需的列,在本例中为"出勤"
  4. 更改"默认值或绑定"属性
  5. enter image description here

相关问题