#asp.net #sql #vb.net
#asp.net #sql #vb.net
Вопрос:
Я новичок в этом и получаю следующую ошибку при запуске моей формы. ‘Строка или двоичные данные будут усечены.Оператор был завершен. ‘
Это код для формы
<form runat="server">
<table style="width:500px">
<tr>
<td>Customer Name*: </td>
<td><asp:TextBox ID="CustomerName" runat="server" MaxLength="50"></asp:TextBox></td>
<td><asp:RequiredFieldValidator id="rfvValidator" runat="server" Enabled="true" ControlToValidate="CustomerName" ErrorMessage="Customer Name is Required." ></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td>Address 1: </td>
<td><asp:TextBox ID="Address1" runat="server" MaxLength="100"></asp:TextBox></td>
</tr>
<tr>
<td>Address 2:</td>
<td><asp:TextBox ID="Address2" runat="server" MaxLength="100"></asp:TextBox></td>
</tr>
<tr>
<td>Address 3:</td>
<td><asp:TextBox ID="Address3" runat="server" MaxLength="100"></asp:TextBox></td>
</tr>
<tr>
<td>Town: </td>
<td><asp:TextBox ID="Town" runat="server" MaxLength="100"></asp:TextBox></td>
</tr>
<tr>
<td>Country:</td>
<td><asp:TextBox ID="Country" runat="server" MaxLength="50"></asp:TextBox></td>
</tr>
<tr>
<td>Postcode:</td>
<td><asp:TextBox ID="PostCode" runat="server" MaxLength="8"></asp:TextBox></td>
</tr>
<tr>
<td>Telephone:</td>
<td><asp:TextBox ID="Telephone" runat="server" MaxLength="50"></asp:TextBox></td>
</tr>
<tr>
<td>Fax:</td>
<td><asp:TextBox ID="Fax" runat="server" MaxLength="50"></asp:TextBox></td>
</tr>
</table>
<asp:Button id="btnSave" Text="Save" runat="server" />
<input type=button name="cancel" value="Cancel" onClick="parent.jQuery.fancybox.close()">
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>
Это мой код для кнопки отправки
Imports System.Data
Imports System.Data.SqlClient
Public Class EditCustomer
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Dim con As SqlConnection
Dim cmd As SqlCommand
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
con = New SqlConnection("Data Source=IPAddress;Initial Catalog=medical01;Persist Security Info=True;User ID=******;Password=******")
con.Open()
cmd = New SqlCommand("INSERT INTO Customer_tbl (customername,address1,address2,address3,town,country,postcode,telephone,fax,isDeleted) VALUES('" amp; CustomerName.Text amp; "','" amp; Address1.Text amp; "','" amp; Address2.Text amp; "','" amp; Address3.Text amp; "','" amp; Town.Text amp; "', " amp; PostCode.Text amp; ", " amp; Telephone.Text amp; "," amp; Fax.Text amp; ", 1)", con)
cmd.ExecuteNonQuery()
Label1.Text = "Customer Added."
con.Close()
End Sub
End Class
Вот моя база данных:
Я получаю эту ошибку:
String or binary data would be truncated.
Оператор был завершен.
Описание: Необработанное исключение возникло во время выполнения текущего веб-запроса. Пожалуйста, просмотрите трассировку стека для получения дополнительной информации об ошибке и о том, где она возникла в коде.
Сведения об исключении: System.Data.SqlClient.SQLException: строка или двоичные данные будут усечены. Оператор был завершен.
Комментарии:
1. можно ли установить для customerid значение autoincrement
2. Не думайте так, если я беру SQL из кода, добавляю значения и запускаю его прямо в SQL, вставка работает и присваивает правильный идентификатор.
Ответ №1:
Вы не заключили в кавычки все поля:
cmd = New SqlCommand("INSERT INTO Customer_tbl (customername,address1,address2,address3,town,country,postcode,telephone,fax,isDeleted)"
amp; "VALUES('" amp; CustomerName.Text amp; "','" amp; Address1.Text amp; "','" amp; Address2.Text amp; "','" amp; Address3.Text amp; "','" amp; Town.Text amp; "', '" amp; PostCode.Text amp; "', '" amp; Telephone.Text amp; "','" amp; Fax.Text amp; "', 1)", con)
Я добавил их PostCode
, Telephone
и Fax
. На этот раз это поможет вам, но вы действительно должны использовать параметры. Это облегчит вашу жизнь и улучшит это утверждение:
cmd = New SqlCommand("INSERT INTO Customer_tbl (customername,address1,address2,address3,town,country,postcode,telephone,fax,isDeleted)"
amp; "VALUES(@customername,@address1,@address2,@address3,@town,@country,@postcode,@telephone,@fax,@isDeleted)", con)
cmd.Parameters.AddWithValue("customername", CustomerName.Text)
cmd.Parameters.AddWithValue("address1", Address1.Text)
cmd.Parameters.AddWithValue("address2", Address2.Text)
cmd.Parameters.AddWithValue("address3", Address3.Text)
cmd.Parameters.AddWithValue("town", Town.Text)
cmd.Parameters.AddWithValue("country", Country.Text)
cmd.Parameters.AddWithValue("postcode", PostCode.Text)
cmd.Parameters.AddWithValue("telephone", Telephone.Text)
cmd.Parameters.AddWithValue("fax", Fax.Text)
cmd.Parameters.AddWithValue("isDeleted", 1)
Комментарии:
1. Я понял, что пишу c # вместо VB.NET , поэтому я обновил код. Хотя должно быть так много изменений.
2. Нет, это идеально, работает хорошо. Спасибо за ваше время.