在向数据库输入数据后,我试图从数据库中“获取”ID 字段 (PK)。获得 ID 后,我想将其输入到另一个表中(出于关系目的)。但是,我的尝试没有成功。
这就是我目前正在做的事情:
int CompanyID;
SqlConnection con = new SqlConnection("Data Source=******;Initial Catalog= ********");
SqlCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "insert into [Company Information] (Expo_Year, Partnership, Company_Name_Pub, Address_Pub, City_Pub, State_Pub, Zip_Pub, Phone_Pub, Fax_Pub, Email_Pub, Contact_Pub, Company_Name_Ex, Address_Ex, City_Ex, State_Ex, Zip_Ex, Phone_Ex, Fax_Ex, Email_Ex, Contact_Ex) VALUES (@Year, @Partnership,@PubCompanyName,@PubAddress,@PubCity,@PubState,@PubZip,@PubPhone,@PubFax,@PubEmail,@PubContact,@ExCompanyName,@ExAddress,@ExCity,@ExState,@ExZip,@ExPhone,@ExFax,@ExEmail,@ExContact) SELECT SCOPE_IDENTITY();";
SqlParameter param = new SqlParameter();
param.ParameterName = "@PubCompanyName";
param.Value = CompanyNmTxt.Text;
cmd.Parameters.Add("@Year", System.Data.SqlDbType.VarChar, 50).Value = Year.Text;
cmd.Parameters.Add("@Partnership", System.Data.SqlDbType.VarChar, 50).Value = DropDownList1.Text;
cmd.Parameters.Add("@PubCompanyName", System.Data.SqlDbType.VarChar,50).Value = CompanyNmTxt.Text;
cmd.Parameters.Add("@PubAddress", System.Data.SqlDbType.VarChar,50).Value = CompanyAddTxt.Text;
cmd.Parameters.Add("@PubCity", System.Data.SqlDbType.VarChar,50).Value = CompanyCtyTxt.Text;
cmd.Parameters.Add("@PubState", System.Data.SqlDbType.Char,2).Value = StateDD.Text;
cmd.Parameters.Add("@PubZip", System.Data.SqlDbType.Int,8).Value = CompanyZipTxt.Text;
cmd.Parameters.Add("@PubPhone", System.Data.SqlDbType.VarChar,50).Value = CompanyPhoneTxt.Text;
cmd.Parameters.Add("@PubFax", System.Data.SqlDbType.VarChar,50).Value = CompanyFaxTxt.Text;
cmd.Parameters.Add("@PubEmail", System.Data.SqlDbType.VarChar,50).Value = CompanyEmailTxt.Text;
cmd.Parameters.Add("@PubContact", System.Data.SqlDbType.VarChar,50).Value = CompanyContactTxt.Text;
cmd.Parameters.Add("@ExCompanyName", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyNmTxt0.Text;
cmd.Parameters.Add("@ExAddress", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyAddTxt0.Text;
cmd.Parameters.Add("@ExCity", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyCtyTxt0.Text;
cmd.Parameters.Add("@ExState", System.Data.SqlDbType.Char, 2).Value = ExStateDD.Text;
cmd.Parameters.Add("@ExZip", System.Data.SqlDbType.Int, 8).Value = ExCompanyZipTxt0.Text;
cmd.Parameters.Add("@ExPhone", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyPhoneTxt0.Text;
cmd.Parameters.Add("@ExFax", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyFaxTxt0.Text;
cmd.Parameters.Add("@ExEmail", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyEmailTxt0.Text;
cmd.Parameters.Add("@ExContact", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyContactTxt0.Text;
CompanyID = (int)cmd.ExecuteScalar();
con.Close();
我得到错误:
用户代码未处理 InvalidCastException;指定的演员表无效。