我必须检查Asp.Net中的数据库中是否存在数据

时间:2014-05-01 10:01:36

标签: c# asp.net sql sql-server sql-server-2008

我有两种方法,一种是插入,更新和删除,另一种是检查数据是否已存在于我的数据库中。所有代码的主要目的是我不想将重复数据插入数据库。

public class DAL : System.Web.UI.Page
{
    SqlConnection connection;
    SqlCommand cmd;
    SqlDataAdapter da;
    DataTable dt;

    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    public int numofrows;

    //Connection Method
    public void Connection()
    {
        connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        connection.Open();
    }

    //This Method will Insert,Update and Delete in Database
    public void InsertUpdateDelete(string query)
    {
        ////connection = new SqlConnection("Data Source=IM-82B70624D72D;Initial Catalog=AppointmentScheduler;User ID=sa;Password=za3452432760za");
        //connection = new SqlConnection(connectionString);
        //connection.Open();
        this.Connection();
        cmd = new SqlCommand(query, connection);
        numofrows = cmd.ExecuteNonQuery();
        connection.Close();
    }

    //This Method will read data From Database
    public DataTable ReadData(string Query)
    {
        this.Connection();
        da = new SqlDataAdapter(Query, connection);
        dt = new DataTable();
        da.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            Response.Redirect("Data already Exist");
        }

        return dt;
    }
}

我必须在index.aspx中使用上述代码。如何在index.aspx中使用上述代码?

我尝试使用但是没有用。

index.aspx代码:

    protected void btnSaveDays_Click(object sender, EventArgs e)
    {
        this.query = "SELECT DaysName FROM Dayss WHERE Day_Id='" + DropDownListDays.SelectedValue + "'";
        dal.ReadData(this.query);

        this.query = "INSERT INTO Dayss VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
        dal.InsertUpdateDelete(this.query);
        Response.Write("Day Inserted Successfully");
    }

但是这段代码无效并产生错误

  

转换失败

1 个答案:

答案 0 :(得分:0)

  

不是Day_Id是int,而Dayss有两列。一个是id,第二个是   名称

然后,使用int类型列值的单引号是没有意义的。单引号用于字符列值。

this.query = "SELECT DaysName FROM Dayss WHERE Day_Id = " + DropDownListDays.SelectedValue ;

如果您只想插入一列,则需要在Dayss表中指定列名称,如

this.query = "INSERT INTO Dayss (YourColumnName) VALUES ('" + DropDownListDays.SelectedItem.Text + "')";

看看INSERT (Transact-SQL)