簡體   English   中英

字符串或二進制數據將被截斷,插入到SQL Server表中

[英]String or binary data would be truncated, insert to SQL Server table

當我嘗試插入到表中時,這是一個運行時異常,在添加更新功能之前它一直在工作。

    private void button1_Click(object sender, EventArgs e)
    {
        Random rndID = new Random();
        int id = rndID.Next(100, 1000);

        SqlConnection connection = new SqlConnection(@"Data Source=DESKTOP-IOHHC7K\SQLEXPRESS;Initial Catalog=CityAppDB;Integrated Security=True");

        SqlCommand command = new SqlCommand("insert into UsersTB(User_ID, Full_Name, Email_Address, Phone_Number, Password) 
             values('" + id.ToString() + "','" + textBox2.Text + "','" +
             textBox3.Text + "','" + textBox4.Text + "','" + 
             textBox5.Text + "')", connection);
        command.Connection.Open();

        if ((ISExisted(id)) && (CheckUserFullName(textBox2.Text)) && (IsValidEmail(textBox3.Text)) && (IsValidPhoneNumber(textBox4.Text)) && (IsValidPassword(textBox5.Text)))
        {
            command.ExecuteNonQuery();//String or binary data would be truncated
            MessageBox.Show("Added.");
            ShowAllUsers();
        }
        else
        {
            MessageBox.Show("Something wrong");
        }

        command.Connection.Close();
    }

此錯誤意味着您正在嘗試更新對於數據庫列定義而言太長的值。

在您的數據庫中,檢查Full_NameEmail_AddressPhone_NumberPassword字段的長度,假設它們被定義為varchar[10] ,此錯誤表示您嘗試使用長度超過10個字符的字符串來更新它們的值,

檢查存儲在以下文本框之一中的值的長度: textBox2.TexttextBox3.TexttextBox4.TexttextBox5.Text 其中之一的文本長於數據庫模式接受的文本。

解決方案1 :增加數據庫中的列大小。

解決方案2 :使用Textbox.MaxLength限制用戶的輸入長度。

該錯誤的唯一目的是:指定的列大小小於要提供的值(只能從表結構中知道)。

再次停止使用字符串串聯傳遞值,而是使用參數化查詢來避免SQL注入。 使用SqlParameter

您的參數化INSERT語句應如下所示

    string query = "insert into UsersTB(User_ID,Full_Name,Email_Address,Phone_Number,Password) values(@User_ID,@Full_Name,@Email_Address,@Phone_Number,@Password)";
    SqlCommand command = new SqlCommand(query, connection);

    command.Parameters.Add("@User_ID",id.ToString());
    command.Parameters.Add("@Full_Name",textBox2.Text);
    command.Parameters.Add("@Email_Address",textBox3.Text);
    command.Parameters.Add("@Phone_Number",textBox4.Text);
    command.Parameters.Add("@Password",textBox5.Text);

暫無
暫無

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

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