将Visual Studio 2017与SQL Server 2016 Express一起使用,并使用以下方法:
protected void subFinish_Click(object sender, EventArgs e)
{
String regPattern = "^\\d{3}-\\d{8}$";
String regPattern2 = "^\\d{11}$";
if (Regex.IsMatch(txtAwbNum.Text, regPattern) || Regex.IsMatch(txtAwbNum.Text, regPattern2))
{
String AwbNum = txtAwbNum.Text;
int doorNum = Convert.ToInt16(ddlDoorNum.SelectedValue);
String driverName = txtDriverName.Text;
String carrier = txtCarrier.Text;
int pieces = Convert.ToInt32(txtPieces.Text);
SqlDecimal GrossWt = SqlDecimal.Parse(txtGrossWt.Text);
SqlDecimal ChargeWt = SqlDecimal.Parse(txtChargeableWt.Text);
String flightNum = ddlFlightNum.ToString();
SqlDateTime date = Convert.ToDateTime(txtDate.Text);
String destination = txtDestination.Text;
String shipper = txtShipper.Text;
Boolean dgCheck = chkDgCheck.Checked;
DateTime today = DateTime.Today;
String dropoffId = DateTime.Today.ToString();
String queryString = "INSERT INTO ExpAwbs (idExpAwbs, Pieces, GrossWt, ChargeWt, Flight, FlightDate, Shipper, Destination, dgCheck) values (@AwbNum, @pieces, @GrossWt, @ChargeWt, @flightNum, @date, @shipper, @destination, @dgCheck);";
String queryString2 = "INSERT INTO Dropoff (idDropoff, DoorNum, Carrier, DriverName, datetime) values (@dropoffID, @doorNum, @carrier, @driverName, @today);";
String connectionString = "Data Source=PCNAME\\SQLEXPRESS;Initial Catalog=TASdb;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, connection);
SqlCommand command2 = new SqlCommand(queryString2, connection);
command.Parameters.AddWithValue("@AwbNum", AwbNum);
command.Parameters.AddWithValue("@pieces", pieces);
command.Parameters.AddWithValue("@GrossWt", GrossWt);
command.Parameters.AddWithValue("@ChargeWt", ChargeWt);
command.Parameters.AddWithValue("@flightNum", flightNum);
command.Parameters.AddWithValue("@date", date);
command.Parameters.AddWithValue("@destination", destination);
command.Parameters.AddWithValue("@shipper", shipper);
command.Parameters.AddWithValue("@dgCheck", dgCheck);
command2.Parameters.AddWithValue("@doorNum", doorNum);
command2.Parameters.AddWithValue("@carrier", carrier);
command2.Parameters.AddWithValue("@driverName", driverName);
command2.Parameters.AddWithValue("@dropoffId", dropoffId);
command.Connection.Open();
command.ExecuteReader();
command.Connection.Close();
command2.Connection.Open();
command2.ExecuteScalar();
command2.Connection.Close();
}
else
{
MessageBox.Show(this, "Invalid AWB. Please check again and re-submit.");
}
}
当我运行它时,我得到一个“字符串或二进制数据将被截断。语句已被终止。”我不明白为什么会这样。我确保所有字段都小于或等于数据库中分配的大小。我唯一质疑的是GrossWt和ChargeWt,因为在数据库中他们的数据类型是Decimal(6,1),但我不认为这是问题,因为我尝试将它们取出来,并没有改变任何东西。下面是相关表的数据库表设计(FlightDate列实际上已更新为datetime数据类型):