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.
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");
This is my
String tempStr = "'''" + shain.searchAffiliation + "'''";
If I use
String affSetStr = " SET #Affiliation = " + tempStr + " ;"; "
Then pass to queryStr, the query will work without any problem. But this query will have sql injection attack.
Now I pass tempStr variable to
SqlParameter shainParameterSearchName = new SqlParameter("#searchAffiliation", tempStr);
Then my query is return an empty list. What is the right way to pass tempStr to SqlParameter("#searchAffiliation", tempStr);?
String tempStr = "'''" + shain.searchAffiliation + "'''";
SqlParameter shainParameterSearchName = new SqlParameter("#searchAffiliation", tempStr);
shainParamsObj.Add(shainParameterSearchName);
affSetStr = " SET #Affiliation = " + tempStr + " ;";
String queryStr = " " +
"DECLARE #Name VARCHAR(50);" +
"DECLARE #Affiliation VARCHAR(50); " +
searchSetStr +
affSetStr +
"DECLARE #AgeStr INT;" +
"DECLARE #AgeEd INT;" +
"SET #AgeStr = #ageStart;" +
"SET #AgeEd = #ageEnd; " +
"DECLARE #fromIdx INT;" +
"DECLARE #toIdx INT; " +
"SET #fromIdx = #fromIndex; " +
"SET #toIdx = #toIndex; " +
"declare #sqll nvarchar(max) = '" +
"SELECT" +
" * " +
" FROM" +
" ( SELECT" +
" ROW_NUMBER() OVER ( " +
" ORDER BY " + orderStr +
" ) AS RowNum, " +
" S1.INCODE id , " +
" DATEDIFF(DAY,S1.KOM005,GETDATE()) age, " +
" CASE " +
" WHEN DATEDIFF(DAY,S1.KOM035,S1.KOM027) < 0 " +
" THEN DATEDIFF(DAY, S1.KOM035, GETDATE()) " +
" ELSE DATEDIFF(DAY, S1.KOM035, S1.KOM027) " +
" END AS lenghtOfService , " +
" S1.KOM001 employeeCode , " +
" S1.KOM005 dbo , " +
" ISNULL(S1.KOM004,0) gender , " +
" S1.KOM035 enterDate , " +
" S1.KOM027 retireDate , " +
" S2.KOM506 postion , " +
" S2.KOM002 name , " +
" S2.KOM003 furigana , " +
" S2.KOM021 phone , " +
" S2.KOM527 email, " +
" S2.KOM512 postCode , " +
" S2.KOM509 contactPerson ," +
" S2.KOM513 address1 , " +
" S2.KOM514 address2," +
" S2.KOM515 tel1, " +
" S2.KOM507 affiliation, " +
" S2.KOM516 tel2, " +
" ISNULL( '+ dbo.CheckIfColumnExist( 'dbo','RIREKI13','R.KOM001', 'CAST(0 as FLOAT)' ) + ' ,0) CP , " +
" ISNULL( '+ dbo.CheckIfColumnExist( 'dbo','RIREKI13','R.KOM002', 'CAST(0 as FLOAT)' ) + ' ,0) NP, " +
" ISNULL( '+ dbo.CheckIfColumnExist( 'dbo','RIREKI13','R.KOM003', 'CAST(0 as FLOAT)' ) + ' ,0) A, " +
" ISNULL( '+ dbo.CheckIfColumnExist( 'dbo','RIREKI13','R.KOM004', 'CAST(0 as FLOAT)' ) + ' ,0) FC, " +
" ISNULL( '+ dbo.CheckIfColumnExist( 'dbo','RIREKI13','R.KOM005', 'CAST(0 as FLOAT)' ) + ' ,0) AC " +
" FROM " +
" dbo.SHAIN1 as S1 " +
" join " +
" dbo.SHAIN2 as S2 " +
" on S1.INCODE = S2.SHAIN " +
" FULL join " +
" RIREKI13 as R " +
" on R.INCODE = S2.SHAIN " +
ifCase +
" ) AS RowConstrainedResult " +
" " +
" WHERE RowNum >= " +
" ' + CONVERT(VARCHAR(12), #fromIdx) + ' " +
" AND RowNum < " +
" ' + CONVERT(VARCHAR(12), #toIdx) + ' " +
" ORDER BY RowNum " +
"'; " +
" exec sp_executesql #sqll ";
List<Shain> shainList = await _context.Shain.FromSql(queryStr,shainParamsObj.ToArray()).ToListAsync();
I want to enter a DATE to my ACCESS DB, the field is DATE/TIME.
The user enter it in a form in this method (text) DD/MM/YYYY
The code:
DATE/TIME object
DateTime Bday = new DateTime(long.Parse(Request.Form["Bday"]));
The SQL QUERY:
cmd.CommandText = "INSERT INTO (Fname,Lname,User,Pass,Email,BiDate,IsAdmin,IsMale) VALUES ('" + fname + "','" + lname + "','" + user + "','" + pass + "','" + email + "',#" + Bday + "#," + admin + "," + male + ")";
Its not working
Remove the long.Parse part
DateTime Bday = DateTime.ParseExact(Request.Form["Bday"], "dd/MM/yyyy",
CultureInfo.InvariantCulture);
cmd.CommandText = "INSERT INTO (Fname,Lname,[User],Pass,Email,BiDate,"
+"IsAdmin,IsMale) " +
"VALUES ('" + fname + "','" + lname + "','" + user + "','" + pass + "','"
+ email + "',#" + Bday.ToString("dd/MM/yyyy") + "#," + admin + "," + male + ")";
Hope this helps!
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);