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

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.

Related

How to insert Persian words into a SQL Server database?

I am just wondering how to insert Persian characters into my service-based database?
When I save my data it shows something like '???'.
I have checked such questions like this. But, the solutions were not useful.
private void button1_Click(object sender, EventArgs e)
{
objConnection.Open();
if (ctypeCheckBox.Checked == true)
st = 1;
else if (ctypeCheckBox.Checked == false)
st = 0;
string query = "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
SDA.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Inserted!");
objConnection.Close();
}
Two things:
Never ever combine your query string with values
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
Should be immediately replaced with
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime)
VALUES(#cname, #cid, #ccredit, #csession, #st, #cstartDateDate, #cendDate, #cStartTime, #cEndTimeB)";
and then you should use
SDA.SelectCommand.Parameters.AddWithValue("cname",cnameTextBox.Text);
for all parameters. This will save you from a lot of problems including SQL injection.
In the database your columns should have nvarchar data type.
Good luck
You should use SqlParameter .Giving example of only one parameter.You can add others as same way.
string query = "INSERT INTO LectureTable(Cname) VALUES(#name)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#name", cnameTextBox.Text);
param.SqlDbType = SqlDbType.String;
cmd.Parameters.Add(param);
.....
}

Insert checkbox value into database SQL

I want to insert the value of a checkbox into the database.
But in the database the column is null.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NAWAF;Initial Catalog=waterreport;Integrated Security=True");
con.Open();
if (checkBox1.CheckState == CheckState.Checked)
{
string chkek = "finish";
}
SqlCommand tump;
SqlCommand orugg;
string tmp = " UPDATE reportonetmp set finish_repair_date='" + textBox1.Text + "', finish_repair_hour='" + textBox2.Text + "', ca_of_problem='" + comboBox1.Text + "', line_type='" + comboBox2.Text + "', situation='" + textBox3.Text + "', diameter_of_pipes ='" + comboBox3.Text + "', timenoww3 ='" + label7.Text + "' WHERE no like '" + label13.Text + "'";
tump = new SqlCommand(tmp, con);
tump.ExecuteNonQuery();
string org = " UPDATE reportone set finish_repair_date='" + textBox1.Text + "', finish_repair_hour='" + textBox2.Text + "', ca_of_problem='" + comboBox1.Text + "', line_type='" + comboBox2.Text + "', situation='" + textBox3.Text + "', diameter_of_pipes ='" + comboBox3.Text + "', timenoww3 ='" + label7.Text + "',checkk ='" + chkek + "' WHERE no like '" + label13.Text + "'";
orugg = new SqlCommand(org, con);
orugg.ExecuteNonQuery();
con.Close();
}
Aside from other problems (like having non-parametrised queries), are you sure that your DB column is called 'checkk'?
If that's correct, I would convert that DB column into a bit one (if you're using SQL Server) or boolean and updating it like this, instead of using an string variable:
"',checkk ='" + checkBox1.Checked
put oncheckchanged on checkbox control in aspx page and if checked means set values to 1 else 0(put if condition in checkedchanged event, so simple).same way you can get from database if value 1 means checkbox ID.Checked like this enough

Adding Data to two Datagridviews

I want to Add Data But I want to Put It In 2 DataGridViews. I tried this but On the 2nd Datagridview I wont Work, It Wont Add, Only In the 1st Datagridview
string query = "insert into dbuser.patientform (patientname,homeaddress,occupation,emailaddress,sex,age,status,birthday,cellphoneno,refferedby,date,diagnosis,treatment)"
+ "values('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.textBox4.Text + "','" + this.comboBox1.SelectedItem + "','" + this.textBox5.Text + "','" + this.comboBox2.SelectedItem + "','" + this.dateTimePicker1.Text + "','" + this.textBox6.Text + "','" + this.textBox7.Text + "','" + this.dateTimePicker2.Text + "','" + this.textBox8.Text + "','" + this.textBox9.Text + "') ;";
string quer = "insert into dbuser.patienthistory (patientname,date,diagnosis,treatment)"
+ "values('" + this.textBox1.Text + this.dateTimePicker2.Text + "','" + this.textBox8.Text + "','" + this.textBox9.Text + "') ;";
MySqlCommand cmd = new MySqlCommand(query, condb);
MySqlCommand cm = new MySqlCommand(quer, condb);
MySqlDataReader myreader;
MySqlDataReader myreader1;
try
{
condb.Open();
myreader = cmd.ExecuteReader();
condb.Close();
condb.Open();
myreader1 = cm.ExecuteReader();
MessageBox.Show("Saved");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
comboBox1.SelectedItem = false;
textBox5.Clear();
comboBox2.SelectedItem = false;
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
dateTimePicker1.Text = null;
condb.Close();
dataset = new DataTable();
da.Fill(dataset);
BindingSource bs = new BindingSource();
bs.DataSource = dataset;
dataGridView1.DataSource = bs;
dataGridView2.DataSource = bs;
da.Update(dataset);
I suggest do followings :
Open and Close Connection one time if two request will use same connection string
Use MySqlDataAdapter for filling data to DataTable.
Set DataTable to DataGridView

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

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);

How to save a picture to an access database table?

I am using this code to save a picture into an access database table:
byte[] fromPath = File.ReadAllBytes(Picture_Path);
byte[] fromPath2 = File.ReadAllBytes(BacksidePicture_Path);
con.Open();
string query = "Insert Into DML_Books_List (" +
"ID,ISNBORCode, Title, Donor, DocType, Edition, Author1, Author2, Author3, " +
"Author4, Translator, Publisher, Subject, USubject, Shelf, Cost, " +
"Language, Pages, Image, BImage, Description, Date) VALUES ('" +
"2" + "','" + ISNB_AddBook_Books_TXT.Text + "', '" +
Title_AddBook_Books_TXT.Text +
"', '" + Donor_AddBook_Books_TXT.Text + "', '" +
DocType_AddBook_Books_CBE.SelectedItem + "', '" +
Edition_AddBook_Books_TXT.Text + "', '" +
Author1_AddBook_Books_TXT.Text + "', '" +
Author2_AddBook_Books_TXT.Text + "', '" +
Author3_AddBook_Books_TXT.Text + "', '" +
Author4_AddBook_Books_TXT.Text + "', '" +
Translator_AddBook_Books_TXT.Text + "', '" +
Publisher_AddBook_Books_CBE.SelectedItem + "', '" +
Subject_AddBook_Books_CBE.SelectedItem + "', '" +
USubject_AddBook_Books_CBE.SelectedItem + "', '" +
Shelf_AddBook_Books_CBE.SelectedItem + "', '" +
Cost_AddBook_Books_TXT.Text + "', '" +
Language_AddBook_Books_CBE.SelectedItem + "', '" +
Pages_AddBook_Books_TXT.Text + "', '" +
#fromPath + "', '" + #fromPath2 + "', '" +
Description_AddBook_Books_MemoEdit.Text + "', '" +
Date_AddBook_Books_TXT.Text + "')";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
myCommand.Connection = con;
myCommand.ExecuteNonQuery();
con.Close();
But it has some problems.
Please Help Me solve this problem.
Thank you
OleDb.OleDbConnection cn = new OleDb.OleDbConnection();
cn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "\\data.mdb";
cn.Open();
byte[] arrImage = null;
string strImage = null;
IO.MemoryStream myMs = new IO.MemoryStream();
//
if ((this.picPhoto.Image != null)) {
this.picPhoto.Image.Save(myMs, this.picPhoto.Image.RawFormat);
arrImage = myMs.GetBuffer;
strImage = "?";
} else {
arrImage = null;
strImage = "NULL";
}
OleDb.OleDbCommand myCmd = new OleDb.OleDbCommand();
myCmd.Connection = cn;
myCmd.CommandText = "INSERT INTO tblstudent(stdid, [name], photo) " + " VALUES(" + this.txtID.Text + ",'" + this.txtName.Text + "'," + strImage + ")";
if (strImage == "?") {
myCmd.Parameters.Add(strImage, OleDb.OleDbType.Binary).Value = arrImage;
}
Interaction.MsgBox("Data save successfully!");
myCmd.ExecuteNonQuery();
cn.Close();
Source
use parameters like below code:
Assume you have two columns in your table called ID and Image. Now you going to insert data using SQL parameters
you need SQL statement like
Insert Into DML_Books_List(ID, [Image]) values (#id, #image)
#id and #image are the given names for parameters. You can set the parameter values by parameter name.
var pic = File.ReadAllBytes(yourFileName);
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("Insert Into DML_Books_List(ID, [Image]) values (#id, #image)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#image", pic);
cmd.ExecuteNonQuery();
}
Use parametrized query..
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=database");
OleDbCommand command = connection.CreateCommand();
imageData = ReadByteArrayFromFile(#"c:\test.jpg");
command.CommandText = "Insert into SomeTable (Name, ImageData) VALUES (#Name, #Img)"
command.Parameters.AddWithValue("#Name", "theName");
command.Parameters.AddWithValue("#Img", imageData);
command.ExecuteNonQuery();

Categories

Resources