簡體   English   中英

如何處理異常不允許從數據類型varchar隱式轉換為varbinary(max)。 在將數據添加到數據庫時

[英]how to handle the exception Implicit conversion from data type varchar to varbinary(max) is not allowed. while adding the data to database

在我的應用程序中,我需要向數據庫中添加數據並將其顯示在gridview中,下面是我不添加id即可使用的代碼,它可以正常工作,但是在我的插入查詢和更新查詢中添加了id之后,我Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.獲取了此異常Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. 我是新來的人,我該如何處理該異常

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection cnn = new SqlConnection();
        cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection "].ConnectionString;
        cnn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select * from  TableName";
        cmd.Connection = cnn;
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataSet ds = new DataSet();
        da.Fill(ds, " TableName ");
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        DataRow drow = ds.Tables["TableName"].NewRow();
        drow["id"] = TextBox1.Text;
        drow["Name"] = TextBox2.Text;
        drow["Designation"] = TextBox3.Text;
        drow["Mobile_No"] = TextBox4.Text;
        drow["Address"] = TextBox5.Text;

        ds.Tables["TableName "].Rows.Add(drow);
        da.Update(ds, " TableName ");
        string script = @"<script language=""javascript"">
        alert('Information have been Saved Successfully.......!!!!!.');
       </script>;";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
    }

由於Id很可能是數字值,因此請勿嘗試為其分配字符串值,而應為該數字生成SQL代碼:

"[...]values(" + Id + ",'" + [...]

而不是(請注意'符號)

"[...]values('" + Id + "','" + [...]

但是,正如Damien_The_Unbeliever指出的那樣,您應該使用SQL參數而不是將整個語句寫為字符串。

如果您將Id值定義為自動分配的身份列,則只需將其從語句的值列表中刪除即可。

例外是不允許從數據類型varchar隱式轉換為varbinary(max)。 使用CONVERT函數運行此查詢。

因此,Sql Server表列和C#id列都必須為varchar或varbinary。 VarBinary(sqltype)= Byte [](.Net)

    byte[] ID=SqlDbType.VarBinary;
    string query = "insert into RegistrationDetails1(Id,FirstName,LastName,MiddleName,Email,LoginID,CreatedDate,Role,Password,Activestatus,passwordstatus,Dept,Eno,Customer) values('" + ID + "','" + txtfname.Text + "','" + txtlname.Text + "','" + txtmname.Text + "','" + txtEmail.Text + "','" + LoginId[0].ToString() + "','" + DateTime.Now + "','" + ddlRole.SelectedItem.ToString() + "','" + Password + "','" + "1" + "','" + "1" + "','" + Dept + "','" + txteno.Text + "','" + Customer + "')";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM