Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll - c#

Below is my add button code, every time I click add button give this error
command.ExecuteNonQuery(); can help me with the problem?
Here is my code
private void button4_Click(object sender, EventArgs e) //Add button
{
tbLecturerId.Select();
string strID, strFirstName, strUsername, strPassword, strDepartment, strEmail;
strID = tbLecturerId.Text;
strFirstName = tbLname.Text;
strUsername = Usernametxt.Text;
strPassword = Passwordtxt.Text;
strDepartment = cbDepartment.Text;
strEmail = tbEmail.Text;
connect.Open();
SqlCommand command = new SqlCommand(#"INSERT INTO Lecturer_tbl (LecturerID,LecturertName, Username,Password, Department,Email) VALUES('" + strID + "','" + strFirstName + "','" + strUsername + "', '" + strPassword + "','" + strDepartment + "' ,'" + strEmail + "')", connect);
command.ExecuteNonQuery();
connect.Close();
displayLectureGrid();
clearLecturertbl();

There is a space and comma problem in your statement. Try this
SqlCommand command = new SqlCommand(#"INSERT INTO Lecturer_tbl (LecturerID,LecturertName,Username,Password,Department,Email) VALUES('" + strID + "','" + strFirstName + "','" + strUsername + "','" + strPassword + "','" + strDepartment + "','" + strEmail + "')", connect);

Related

I wanted to upload a profile for my site but there's an error in the #FileUpload2 line

When I try to upload a profile for my site I get an exception in this line
FileUpload2.SaveAs(Server.MapPath("~/moreinfo/") + Path.GetFileName(FileUpload2.FileName));
Code:
protected void btnUpload_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseCollege"].ConnectionString);
FileUpload1.SaveAs(Server.MapPath("~/logos/") + Path.GetFileName(FileUpload1.FileName));
String link = "logos/" + Path.GetFileName(FileUpload1.FileName);
FileUpload2.SaveAs(Server.MapPath("~/moreinfo/") + Path.GetFileName(FileUpload2.FileName));
String filename = "moreinfo/" + Path.GetFileName(FileUpload2.FileName);
// Label1.Text = Session["UserName"].ToString();
String query = "INSERT INTO Notice VALUES('" + link + "','" + filename + "','" + txtrequirements.Text + "','" + txtlocation.Text + "','" + txtdate.Text + "','" + txtCompany.Text + "','" + txtwebsite.Text + "','" + Session["Username"] + "')";
// String query = "Insert into Notice values('" + link + "','" + Session["UserName"] + "','" + txtCompany.Text + "','" + txtwebsite.Text + "','" + txtrequirements.Text + "','" + txtlocation.Text + "','" + txtdate.Text + "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open(); ;
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, GetType(), "Popup", "successalert();", true);
txtrequirements.Text = "";
txtlocation.Text = "";
txtdate.Text = "";
txtCompany.Text = "";
txtwebsite.Text="";
}
Exception:
An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code

Asp.net with c# , insert and update in save button

I am using one button named as Button 1. In Button 1 button I perform insert as well as update. I can insert a new row. But when I update the row I had a error on that:
"ORA-00933: SQL command not properly ended ".
My code is:
protected void Button1_Click(object sender, EventArgs e)
{
string UserName = "UserName";
Session["UserName"] = lb1.Text;
TextBox TextBox1 = (TextBox)FindControl("TextBox1");
Label label11 = (Label)FindControl("label11");
TextBox TextBox2 = (TextBox)FindControl("TextBox2");
TextBox TextBox3 = (TextBox)FindControl("TextBox3");
TextBox TextBox4 = (TextBox)FindControl("TextBox4");
DropDownList DropDownList3 = (DropDownList)FindControl("DropDownList3");
DropDownList DropDownList1 = (DropDownList)FindControl("DropDownList1");
TextBox TextBox5 = (TextBox)FindControl("TextBox5");
TextBox TextBox6 = (TextBox)FindControl("TextBox6");
DropDownList DropDownList2 = (DropDownList)FindControl("DropDownList2");
TextBox TextBox7 = (TextBox)FindControl("TextBox7");
TextBox TextBox8 = (TextBox)FindControl("TextBox8");
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from
service_master where req_no='" + this.TextBox1.Text.ToString() + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
string sql1 = "update service_master set req_no='" + this.TextBox1.Text.ToString() + "' , req_dt='" + label11.Text.ToString() + "',req_by='" + Session["UserName"].ToString() + "', ser_cd='" + TextBox3.Text.ToString() + "',serv_desc= '" + TextBox4.Text.ToString() + "',serv_grp_cd='" + DropDownList3.SelectedItem.Value.ToString() + "',base_uom_cd= '" + DropDownList1.SelectedItem.Value.ToString() + "',sac_cd='" + TextBox5.Text.ToString() + "',ser_long_desc='" + TextBox6.Text.ToString() + "',tax_ind='" + DropDownList2.SelectedItem.Value.ToString() + "',active_ind= '" + TextBox7.Text.ToString() + "',del_ind='" + TextBox8.Text.ToString() + "' where req_no='" + this.TextBox1.Text.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(sql1, con);
cmd.ExecuteNonQuery();
WebMsgBox.Show("Data Successfully Updated");
}
else
{
string sql = "insert into service_master(req_no,req_dt,req_by,ser_cd,serv_desc,serv_grp_cd,base_uom_cd,sac_cd,ser_long_desc,tax_ind,active_ind,del_ind ) values(" + this.TextBox1.Text.ToString() + ",'" + label11.Text.ToString() + "', '" + Session["UserName"].ToString() + "', '" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "','" + DropDownList3.SelectedItem.Value.ToString() + "','" + DropDownList1.SelectedItem.Value.ToString() + "','" + TextBox5.Text.ToString() + "','" + TextBox6.Text.ToString() + "','" + DropDownList2.SelectedItem.Value.ToString() + "','" + TextBox7.Text.ToString() + "','" + TextBox8.Text.ToString() + "')";
OleDbCommand com = new OleDbCommand(sql, con);
com.ExecuteNonQuery();
WebMsgBox.Show("The data for request number" + TextBox1.Text + "is saved");
}
con.Close();
}
}
Your query should look something like this
//insert query
//string sql1 = "INSERT INTO Test(id, name) VALUES(#User_FirstName, #User_LastName)";
//update sample query
string sql1 = "UPDATE Test SET User_FirstName=#User_FirstName, User_LastName=#User_LastName";
SqlCommand cmd = new SqlCommand(smt, _connection);
cmd.Parameters.Add("#User_FirstName", FirstName.Text);
cmd.Parameters.Add("#User_LastName", LastName.Text);
Always use Parameters to preform any database actions. Using user input is very dangerous, look up sql injections.

If combobox not selected any item enter empty string into Access database

When I enter a data in my Access database, if I do not select any item in the combobox, I get an error of null exception. So how can I make sure that if I did not select any items, empty data is inserted into my database?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
if (comboBox10.SelectedItem == null)
{
comboBox10.Text = " ";
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
You can check if the SelectedItem property is null, then set a temp variable to use in your query string.
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
Then use comboBox10Text in your query string.
Edit:
// Check if comboBox10.SelectedItem is null, set temp variable
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// Update query string to use comboBox10Text instead of accessing SelectedItem
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
You can have a null check and change the condition
If(comboBox10.SelectedItem != null)
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
}
else
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + "" + "')";
}

SQL Command Error

here is the story :
Im trying to insert some data form the form to my data base but some thing wrong with the syntax "Vs Say so" but i can't find the mistake and some one help ?
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=ltdb;UID=root;Password=1234;port=3306");
try
{
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
conn.Open();
MySqlCommand cmd = new MySqlCommand(command, conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Saved !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
INSERT INTO invoice companyName, ... missing opening brace, correct is
INSERT INTO invoice(column1, column2, ...) VALUES (#Columns1, #columns2, ...)
Coming to point 2: you're open for sql-injection. Use parameterized queries.
Change your
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
To
string command = "INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES (#name,#rate,#vatno,#tinno,#adline1,#adline2,#city)";
command.Parameters.AddWithValue("name",txtname.Text);
command.Parameters.AddWithValue("rate",txtrate.Text);
....
*Edit: For more info, google "c# parameterized sql"
You put Wrong bracket
INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES ('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');

Syntax error in INSERT INTO statement OleDBCOmmand

I have an issue when trying to insert Rows from Datatable into an Excel sheet. I keep getting syntax error but when i insert the sql string into mssql server there is no issue verifying the sql statement.
this is my code:
public void InsertData(DataTable kpiData)
{
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\KPIReports\";
string fileName = #"\Return_Report - " + DateTime.Today.ToShortDateString() + ".xlsx";
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
{
File.Delete(file);
}
File.Copy(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\ReportTemp.xlsx", folderPath + fileName);
System.Data.OleDb.OleDbConnection connection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
connection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + folderPath + fileName + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=YES;\"");
connection.Open();
myCommand.Connection = connection;
foreach (DataRow row in kpiData.Rows)
{
string weight = row[11].ToString().Replace(',', '.');
sql = "Insert into [Data$] (WeekNr, AccountNumber, Barcode, Barcode2, PickupDate, DeliveryCustID, DeliveryAlias, PickupCustID, PickupAlias, DeliveryAttentionName, Coli, Weight, Note, DeliveryType, " +
"Name, Street, HouseNo, Postal, City, DanxCode, Receiver, PODTime, OnTime, [Service]) Values('" + row[0].ToString() + "','" + row[1].ToString() + "','" + row[2].ToString() + "','" + row[3].ToString() + "','" + row[4].ToString() + "','"
+ row[5].ToString() + "','" + row[6].ToString() + "','" + row[7].ToString() + "','" + row[8].ToString() + "','" + row[9].ToString() + "','" + row[10].ToString() + "','" + weight + "','" + row[12].ToString() + "','" + row[13].ToString() + "','"
+ row[14].ToString() + "','" + row[15].ToString() + "','" + row[16].ToString() + "','" + row[17].ToString() + "','" + row[18].ToString() + "','" + row[19].ToString() + "','" + row[20].ToString() + "','" + row[21].ToString() + "','" + row[22].ToString() + "','" + row[23].ToString() + "')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
}
myCommand.Dispose();
connection.Close();
releaseObject(myCommand);
releaseObject(connection);
}
and this is the sql string:
Insert into [Data$] (WeekNr, AccountNumber, Barcode, Barcode2, PickupDate, DeliveryCustID, DeliveryAlias, PickupCustID, PickupAlias, DeliveryAttentionName, Coli, Weight, Note, DeliveryType, Name, Street, HouseNo, Postal, City, DanxCode, Receiver, PODTime, OnTime, [Service]) Values('20','44730629311','12626707007','0681739685','10-05-2014 15:22:13','xxxxx','xxxx','xxxxx','Asker','','1','0.2','','N','xxx','xxxx','111','0665','xxx','xxx','xxxx','13-05-2014 07:00:00','OT','Reverse')
I cant seem to find the problem. I hope someone cant help me..
thanks in advance.
I have found the issue.
The problem was that i didnt have the Note column in brackets. Because Note is a reserved word then it has to have brackets around it like so: [Note]

Categories

Resources