Related
This is my code:
{
string To = Server.HtmlEncode(Request.Cookies["userInfo"]["Email"]).ToString();
string name = Server.HtmlEncode(Request.Cookies["userInfo"]["Name"]).ToString();
string Subject = "IQC Non-leather Status";
string email_body = "Item has been checked by QC with the following details.. ";
string sImage = System.Web.HttpContext.Current.Server.MapPath("~/Content/Uploads/image.jpg");
DataTable dtqc = new ifs_ShipmentInfo_DAL().qc_po_info(site, IQC_STORE_SL);
email_body += #"<table>";
if (dtqc.Rows.Count > 0)
This is the mail body:
{
DataRow dr = dtqc.Rows[0];
email_body += "<tr><td>Supplier Name</td><td>:</td><td>" + Convert.ToString(dr["SUPPLIER_NAME"]) + "</td></tr>";
email_body += "<tr><td>PO NO</td><td>:</td><td>" + Convert.ToString(dr["PO_NO"]) + "</td></tr>";
email_body += "<tr><td>Invoice No</td><td>:</td><td>" + Convert.ToString(dr["COMMERCIAL_INV_NO"]) + "</td></tr>";
email_body += "<tr><td>Invoice recvd date</td><td>:</td><td>" + Convert.ToString(dr["DATE_OF_RECEIVING"]) + "</td></tr>";
email_body += "<tr><td>Part No</td><td>:</td><td>" + Convert.ToString(dr["PART_NO"]) + "</td></tr>";
email_body += "<tr><td>Part Description</td><td>:</td><td>" + Convert.ToString(dr["PART_DESC"]) + "</td></tr>";
email_body += "<tr><td>Invoice Qnty</td><td>:</td><td>" + Convert.ToString(dr["INVOICE_QTY"]) + "</td></tr>";
email_body += "<tr><td>Final Result</td><td>:</td><td>" + INSPECTION_RESULT + "</td></tr>";
email_body += "<tr><td>Reason</td><td>:</td><td>" + insRemarks + "</td></tr>"
+ "<tr><td>Inspected Qnty</td><td>:</td><td>" + INSPECTION_QTY + "</td></tr>"
+ "<tr><td>Accepted Qnty</td><td>:</td><td>" + ACCEPTED_QTY + "</td></tr>"
+ "<tr><td>Rejected Qnty</td><td>:</td><td>" + REJECTED_QTY + "</td></tr>"
+ "<tr><td>Fully Rejected Qnty</td><td>:</td><td>" + FINAL_REJECTED_QTY + "</td></tr>"
+ "<tr><td>Inspected By</td><td>:</td><td>" + INSPECTED_BY + "</td></tr>"
Trying to send image like this:
+ "<tr><td>Defective Picture</td><td>:</td><td><img src='" + sImage + "'width='100'height='100'alt='img'style='margin:20px 0px 0px 20px'/></td></tr>";
}
email_body += "</table>";
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: String or binary data would be truncated.
This is my code
SqlCommand cmd = new SqlCommand("insert into students (S_username,S_password,S_f_name,S_m_name,S_l_name,S_father_name,S_mother_name,S_dob,S_gender,S_cast_id,S_religion,S_father_occu,S_mothers_occu,S_annual_income,S_local_add,S_p_address,S_L_pincode,S_p_pincode,S_L_city,S_p_city,S_L_state,S_p_state,S_department,S_semistor,s_mob_no,s_parents_mob_no,s_email,S_aadhar_no) values ('" + txtuName.Text + "','" + txtpass.Text + "','" + Txtfname.Text + "','" + Txtmname.Text + "', '" + Txtlname.Text + "','" + TxtFthname.Text + "','" + Txtmname.Text + "','" + TextBox2.Text + "','" + DropDownList2.SelectedItem.Value + "', '" + DropDownList.SelectedItem.Value + "','" + txtrel.Text + "','" + Txtfoccu.Text + "','" + Txtmoccu .Text + "','" + DropDownList1.SelectedItem.Value + "','" + Txtlcaladd.Text + "','" + TxtpAdd.Text + "','" + Txtzipcode.Text + "', '" + Txtzipc.Text + "','" + Txtcity.Text + "', '" + Textcity.Text + "', '" + Txtstate.Text + "', '" + Textstate.Text + "', '" + DropDownList3.SelectedItem.Value + "', '" + Txtsem.Text + "','" + Txtmb.Text + "','" + Txtparmb + "','" + TxtEmail.Text + "','" + TxtAdhno.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
txtuName.Text = string.Empty;
txtpass.Text = string.Empty;
Txtfname.Text = string.Empty;
Txtmname.Text = string.Empty;
Txtlname.Text = String.Empty;
TxtFthname.Text = String.Empty;
Txtmname.Text = String.Empty;
TextBox2.Text = String.Empty;
DropDownList2.DataTextField = "TextFiled";
DropDownList.DataTextField = "TextFiled";
txtrel.Text = string.Empty;
Txtfoccu.Text = string.Empty;
Txtmoccu.Text = string.Empty;
DropDownList1.DataTextField = "TextValues";
Txtlcaladd.Text = string.Empty;
TxtpAdd.Text = string.Empty;
Txtzipcode.Text = string.Empty;
Txtzipc.Text = string.Empty;
Txtcity.Text = string.Empty;
Textcity.Text = string.Empty;
Txtstate.Text = string.Empty;
Textstate.Text = string.Empty;
DropDownList3.DataTextField = "TextFiled";
Txtsem.Text = string.Empty;
// objnew.lastAppointmentNo = Convert.ToInt32(Request["txtLastAppointmenNo"]);
int s_mob_no = Convert.ToInt32(Request.QueryString.Get("s_mob_no"));
int s_parents_mob_no = Convert.ToInt32(Request.QueryString.Get(" s_parents_mob_no"));
//Txtmb.Text = string.Empty;
// Txtparmb.Text = string.Empty;
TxtEmail.Text = string.Empty;
int S_aadhar_no = Convert.ToInt32(Request.QueryString.Get(" S_aadhar_no"));
con.Close();
Console.WriteLine("Success");
Two things to do here:
Use parameterized queries to avoid SQL injection:
string query = "insert into students (username, ...) VALUES(#uname, ...)";
SqlCommand cmd = new SqlCommand(query, con);
//Passing values to Parameters
cmd.Parameters.AddWithValue("#uname", "Value");
Check the parameter values are in accordance with the columns in your SQL table both datatype and size. I think it is the size which is causing the problem in your case. You are trying to insert data that has a greater length than what you have defined for that column in the SQL table.
use parametrized queries so you avoid SQL Injection attacks
//Replaced Parameters with Value
string query = "insert into students (S_username, ...) VALUES(#username, ...)";
SqlCommand cmd = new SqlCommand(query, con);
//Pass values to Parameters
cmd.Parameters.AddWithValue("#username", "XYZ_Value");
cmd.Parameters.AddWithValue("#...", "$20");
I am trying to solve an error ,I created a variable to b store data that is in an Excel sheet. The error occurs when I try to insert the data that in SQL Server, in the query. Thanks for the help .
Code: variable declaration:
String valmoradafiscaligualmoradalocal = "";
Information search code:
Case 47: // column 21
If ((WS.Cells [row, Collation] as Excel.Range) .Value)! = Null)
{
Valmoradafiscaligualmoradalocal = Convert.ToString ((WS.Cells [row, Contcoluna] as Excel.Range) .Value);
}
continue;
Insert code in sql server:
}
break;
}
If (WS! = Null)
{
SqlCommand cmd = new SqlCommand ();
cmd.CommandText = "INSERT tabela_sacc (Grupo,Tipo_de_Instalacao,SubGrupo,Nr_Cliente,Data_Entidade,Situacao_da_entidade,Tipo_Entidade,Nome,Contribuinte,Tipo_Documento,Numero_Documento,Nr_Ident,Cod_Cliente_Sistema_Antigo,Entidade_Pagadora,Nome_Entidade_Pagadora,Numero_Contrato,Data_Contrato,Tipo_Contrato,Tipo_Sensibilidade,Tipo_de_Fatura,Nivel_de_Contador,Morada_de_Envio,Localizacao,Tipo_de_Medicao_Telemetria,Data_Vigencia,Ultimo_Dia_Estimado,Ultimo_Dia_Real,Ultimo_Dia_Faturado,Data_Ultima_Fatura,Data_Proxima_Fatura,Data_Situacao,Consumo_Medio_Real,Estimativa,Grupo_Contador,N_Contador,N_Referencia_Contador,Selos_do_Contador,Data_Instalacao,Leit_Cont_Simples_a_Data_Inst,Leit_Cont_Secundaria_a_Data_Inst,Leit_Cont_Principal_a_Data_Inst,Numero_Fabricante,Fabricante,Modelo_do_Contador,Calibre,Morada_Fiscal_Igual_a_Morada_Local,N_Rua_A,Rua_A,Policia_A,Andar_A,Localidade_A,Freguesia_A,Cod_Postal_A,Des_Postal_A,Zona_Postal_A,N_Rua_C,Rua_C,Policia_C,Andar_C,Localidade_C,Freguesia_C,Cod_Postal_C,Des_Postal_C,Zona_Postal_C,Nome_Fatura,N_da_Instalacao,N_Predio,Ramal,Ramal_Associado,Ramal_Saneamento,Anotacoes,Anotacoes_Ramal_Saneamento,Zona_Abastecimento,ZMC,Classe_Consumo,Tipo_Consumo,Grupo_Tarifario,Situacao,Zona,Area,Local,Local_em_Vigor,Tipo_Abastecimento,Caracteristica_Local,Calibre_Local,Local_Totalizador) VALUES ('" + valgrupo + "','" + valsubgrupo + "' ,'" + valtpinstalacao.ToString() + "','" + valnrcliente + "','" + valdataentidade.ToString("MM/dd/yyyy") + "','" + valsituacaoentidade + "','" + valtpentidade + "','" + valnome + "','" + valcontrbuinte + "','" + valtpdoc + "','" + valndoc + "','" + valnridentidade + "','" + valcodclisistemaantigo + "','" + valentidadepagadora + "','" + valnomeentidadepagadora + "','" + valncontrato + "','" + valdatacontrato.ToString("MM/dd/yyyy") + "','" + valtpcontrato + "','" + valtpsensibilidade + "','" + valtpfatura + "','" + valnivelcontador + "','" + valmoradaenvio + "','" + vallocalizacao + "','" + valtpmedicaotelemetria + "','" + valdatavigencia.ToString("MM/dd/yyyy") + "','" + valultimodiaestimado.ToString("MM/dd/yyyy") + "','" + valultimodiareal.ToString("MM/dd/yyyy") + "','" + valultimodiafaturado.ToString("MM/dd/yyyy") + "','" + valdataultimafatura.ToString("MM/dd/yyyy") + "','" + valdataproximafatura.ToString("MM/dd/yyyy") + "','" + valdatasituacao.ToString("MM/dd/yyyy") + "','" + valconsumomedioreal + "','" + valestimativa + "','" + valgrupocontador + "','" + valncontador + "','" + valnreferenciacontador + "','" + valselocontador + "','" + valdatainstalacao.ToString("MM/dd/yyyy") + "','" + valleiturasimplescontadoradatainst + "','" + valleituraprincipalcontadoradatainst + "','" + valleiturasecundariacontadoradatainst + "','" + valnrfabricante + "','" + valfabricante + "','" + valmodelocontador + "','" + valcalibre + "','" + valmoradafiscaligualmoradalocal.ToString() + "','" + valnruaa + "','" + valruaa + "','" + valpoliciaa + "','" + valandara + "','" + vallocalidadea + "','" + valfreguesiaa + "','" + valcodposltala + "','" + valdespostala + "','" + valzonapostala + "','" + valnruac + "','" + valruac + "','" + valpoliciac + "','" + valandarc + "','" + vallocalidadec + "','" + valfreguesiac + "','" + valcodpostalc + "','" + valdespostalc + "','" + valzonapostalc + "','" + valnomefatura + "','" + valninstalacao + "','" + valnpredio + "','" + valramal + "','" + valramalassociado + "','" + valramalsaneamento + "','" + valanotacoes + "','" + valanotacoesramalsaneamento + "','" + valzonaabastecimento + "','" + valzmc + "','" + valclasseconsumo + "','" + valtipoconsumo + "','" + valgrupotarifario + "','" + valsituacao + "','" + valzona + "','" + valarea + "','" + vallocal + "','" + vallocalemvigor + "','" + valtpabastecimento + "','" + valcaracteristicalocal + "','" + valcalibrelocal + "','" + vallocaltotalizador + "')";
Connection.Open();
Cmd.Connection = connection;
Cmd.CommandType = CommandType.Text;
Cmd.ExecuteNonQuery();
Connection.Close();
valmoradafiscaligualmaradalocal= null;
break;
}
}
MessageBox.Show ("end");
}
}
I think you need to check the column in SQL, because seems like the 'morada_Fiscal_Igual_a_Morada_Local' column is a tinyint type and not a text to get the string "Não"
If you are trying to make a boolean type, use the type "bit"
For now, you can make this:
"VALUES ('" + valmoradafiscaligualmoradalocal.ToString() == "Não" ? "0" : "1" + "')"
PS: Na proxima vez preste atenção, se o campo for um tinyint, ou bit, quer dizer que ele quer receber 0 ou 1, assim como em um campo de verdadeiro ou falso.
I am trying to fill a list from a database. Here is my code:
string cur = dInstructorSelect.SelectedValue.Substring(dInstructorSelect.SelectedValue.IndexOf(" - ") + 3);
SqlCommand cmdInsCourses = new SqlCommand("select * from CourseTable where InstructorID=#cur", con);
cmd.Parameters.AddWithValue("#cur", cur);
SqlDataAdapter da = new SqlDataAdapter(cmdInsCourses);
DataTable dt = new DataTable();
da.Fill(dt);
Here, i declare a string variable cur, which returns 4 as i expect. The problem is, when i debugged, there is an error saying that Must declare the scalar variable "#cur". I cannot see what is problematic here. Can anyone help?
Thanks
Edit: Here is the full code:
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
int result;
string queryCourseCount = "select count (*) from CourseTable";
SqlCommand countCommand = new SqlCommand(queryCourseCount, con);
con.Open();
int courseCount = 1001 + Convert.ToInt32(countCommand.ExecuteScalar());
string crn = (MyGlobals.currentYear % 100).ToString() + (MyGlobals.currentTerm == "Spring" ? 2 : 1) + courseCount.ToString().Substring(1, 3);
string instructor = dInstructorSelect.SelectedValue.Substring(dInstructorSelect.SelectedValue.IndexOf(" - ")+3);
string subject = dSubject.SelectedValue, courseNumber=tCourse.Text, courseName= tCourseName.Text ;
string courseDescription = tCourseDescription.Text, capacity=tCapacity.Text;
string currentTerm=MyGlobals.currentTerm + " " + MyGlobals.currentYear.ToString();
string level=dLevel.SelectedValue, credit=tCredit.Text;
string query1 = "insert into CourseTable(InstructorID,CourseCode,CourseNumber,CourseName,Term, CRN,Level,Credit,Description,Capacity) values(#instructor,#subject,#courseNumber,#courseName,#currentTerm,#crn,#level,#credit,#courseDescription,#capacity)";
SqlCommand cmd = new SqlCommand(query1, con);
cmd.Parameters.AddWithValue("#instructor", instructor);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#courseName", courseName);
cmd.Parameters.AddWithValue("#currentTerm", currentTerm);
cmd.Parameters.AddWithValue("#crn", crn);
cmd.Parameters.AddWithValue("#level", level);
cmd.Parameters.AddWithValue("#credit", credit);
cmd.Parameters.AddWithValue("#courseDescription", courseDescription);
cmd.Parameters.AddWithValue("#capacity", capacity);
string query2 = "";
string query3 = "";
if (cbPreq1.Checked)
{
query2 = "insert into PrereqTable(CourseCode,CourseNumber,Term,pCourseCode,pCourseNumber) values ('"
+ dSubject.SelectedValue + "'" + "," + "'" + tCourse.Text + "'" + "," + "'" + MyGlobals.currentTerm + " " + MyGlobals.currentYear.ToString()
+ "'" + "," + "'" + dPrereq1.SelectedValue.Substring(0, dPrereq1.SelectedValue.Length - 3) + "'" + "," + "'" + dPrereq1.SelectedValue.Substring(dPrereq1.SelectedValue.Length - 3, 3) + "'" + ")";
}
if (cbPreq2.Checked)
{
query3 = "insert into PrereqTable(CourseCode,CourseNumber,Term,pCourseCode,pCourseNumber) values ('"
+ dSubject.SelectedValue + "'" + "," + "'" + tCourse.Text + "'" + "," + "'" + MyGlobals.currentTerm + " " + MyGlobals.currentYear.ToString()
+ "'" + "," + "'" + dPrereq2.SelectedValue.Substring(0, dPrereq2.SelectedValue.Length - 3) + "'" + "," + "'" + dPrereq2.SelectedValue.Substring(dPrereq2.SelectedValue.Length - 3, 3) + "'" + ")";
}
string query4="";
if (cbtime1.Checked)
{
query4 = "insert into TimeTable(CourseCode, CourseNumber, Term, StartHour, EndHour, Day) values ('"
+ dSubject.SelectedValue + "'" + "," + "'" + tCourse.Text + "'" + "," + "'" + MyGlobals.currentTerm + " " + MyGlobals.currentYear.ToString()
+ "'" + "," + "'" + dHourStart.SelectedValue + "'" + "," + "'" + dHourEnd.SelectedValue + "'" + "," + "'" + dDay.SelectedValue + "'" + ")";
}
string query5 = "";
if (cbtime2.Checked)
{
query5 = "insert into TimeTable(CourseCode, CourseNumber, Term, StartHour, EndHour, Day) values ('"
+ dSubject.SelectedValue + "'" + "," + "'" + tCourse.Text + "'" + "," + "'" + MyGlobals.currentTerm + " " + MyGlobals.currentYear.ToString()
+ "'" + "," + "'" + dHourStart2.SelectedValue + "'" + "," + "'" + dHourEnd2.SelectedValue + "'" + "," + "'" + dDay2.SelectedValue + "'" + ")";
}
string query6="";
if (cbtime3.Checked)
{
query6 = "insert into TimeTable(CourseCode, CourseNumber, Term, StartHour, EndHour, Day) values ('"
+ dSubject.SelectedValue + "'" + "," + "'" + tCourse.Text + "'" + "," + "'" + MyGlobals.currentTerm + " " + MyGlobals.currentYear.ToString()
+ "'" + "," + "'" + dHourStart3.SelectedValue + "'" + "," + "'" + dHourEnd3.SelectedValue + "'" + "," + "'" + dDay3.SelectedValue + "'" + ")";
}
SqlCommand cmd1, cmd2, cmd3, cmd4, cmd5, cmd6;
bool correctTime = false;
List<String> timeTable = new List<string>();
List<Course>instCourses = new List<Course>();
string tableName = "InstructorTable";
// String name = "", surname = "", email = "";
// CreateUser(con, tableName, ref name, ref surname, ref email);
// MyGlobals.instructor = new Instructor(Convert.ToInt32(idBox.Text), "Active", email, name, surname, passwordBox.Text);
string cur = dInstructorSelect.SelectedValue.Substring(dInstructorSelect.SelectedValue.IndexOf(" - ") + 3);
SqlCommand cmdInsCourses = new SqlCommand("select * from CourseTable where InstructorID=#cur", con);
cmd.Parameters.AddWithValue("#cur", cur);
SqlDataAdapter da = new SqlDataAdapter(cmdInsCourses);
DataTable dt = new DataTable();
da.Fill(dt);
Note: I know there are some queries that are not parametrized, i will fix them.
Try prefixing your parameter with #:
cmdInsCourses.Parameters.AddWithValue("#cur", cur);
Try adding the scalar variable "#cur" rather than "cur":
cmd.Parameters.AddWithValue("#cur", cur);
Try like this...
SqlCommand cmdInsCourses =
new SqlCommand("select * from CourseTable where InstructorID=#cur", con);
cmdInsCourses.Parameters.Add("cur", SqlDbType.VarChar).Value = cur;
EDIT : The Problem lies that you are adding parameters to cmd, not to cmdInsCourses, I have changed the code, just look into that.
I am getting username and password from the user in a registration form and saving the same in MS access database. When I do that, the password column in my database shows "null". So the login page does not work properly. What do I do?
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =DriverManager.getConnection("Jdbc:Odbc:db5");
Statement smt = con.createStatement();
String str =
"insert into table1(name1,sex,age,email,pwd,info) "
+ "values('" + name + "','" + sex + "','" + age + "','"
+ email + "','" + pwd + "','" + info + "')";
int val=smt.executeUpdate(str);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =DriverManager.getConnection("Jdbc:Odbc:db5");
Statement smt = con.createStatement();
String str =
"insert into table1(name1,sex,age,email,pwd,info) "
+ "values('" + name + "','" + sex + "','" + age + "','"
+ email + "','" + pwd + "','" + info + "')";
smt.executeUpdate(str);