How to use select sub Query in insert statement? - c#

I am trying to insert some values into a database, using insert statement. I have to use select statement as well to get from another table the key that corresponds to the option selected.
I tried several queries but none of them worked.
string query3 = "insert into students (FirstName, LastName, FatherName,
Email, DateBirth, DateReg, Adress, Gender, Specialization, Country,
Province, City) values ('"
+ this.txt_fname.Text + "','" + this.txt_lname.Text + "','"
+ this.txt_fathername.Text + "','" + this.txt_email.Text + "','"
+ this.date_birth.Text + "', '" + this.date_reg.Text + "','"
+ this.txt_adress.Text + "','" + this.Gender
+ "', (select specialization_id from specialization where SpecializationName = '" + this.specialization.Text
+ "'),
(select country_id from country where CountryName ='" + this.comboBox2.Text
+ "'),(select province_id from province where ProvinceName ='"
+ this.comboBox4.Text
+ "'),(select city_id from city where CityName ='"+ this.comboBox3.Text + "');";
I expect the output "saved" but I get {"Incorrect syntax near ';'."}
When I use:
'" + ("SELECT specialization_id from specialization where SpecializationName =" + this.specialization.Text)+ "'
instead of (wrote above):
(select specialization_id from specialization where SpecializationName = '" + this.specialization.Text + "')
I get:
{"Conversion failed when converting the varchar value 'SELECT specialization_id from specialization where SpecializationName =Informatica Economica' to data type int."}

My usual caveat, I'm not a C# programmer, I barely know it, but the documenation I linked before was more than enough for me to write this properly:
string commandText = "INSERT INTO dbo.student (FirstName, LastName, FatherName, Email, DateBirth,DateReg, Adress, Gender, Specialization, Country, Province,City) " +
"SELECT #FirstName,#LastName, #Fathername, #Email, #DateBirth, #DateReg, #Address, #Gender, s.specialization_id, c.country_id, p.province_id, cy.city_id " +
"FROM (SELECT specialization_id FROM dbo.specialization WHERE SpecializationName = #Specialization) s " +
"CROSS APPLY (select country_id from country where CountryName = #Country) c " +
"CROSS APPLY (select province_id from province where ProvinceName = #Province) p " +
"CROSS APPLY (select city_id from city where CityName = #City) cy;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add(#FirstName, SqlDbType.VarChar,50).Value = this.txt_fname.Text;
command.Parameters.Add(#LastName, SqlDbType.VarChar,50).Value = this.txt_lname.Text;
command.Parameters.Add(#Fathername, SqlDbType.VarChar,50).Value = this.txt_fathername.Text;
command.Parameters.Add(#Email, SqlDbType.VarChar,50).Value = this.txt_email.Text;
command.Parameters.Add(#DateBirth, SqlDbType.Date).Value = this.date_birth.Text; //Shouldn't this be a date picker object?
command.Parameters.Add(#DateReg, SqlDbType.Date).Value = this.date_reg.Text; //Shouldn't this be a date picker object?
command.Parameters.Add(#Address, SqlDbType.VarChar,200).Value = this.txt_adress.Text; //It's spelt Address (2 d's)
command.Parameters.Add(#Gender, SqlDbType.VarChar,10).Value = this.Gender; //Why did this not have the Text property?
command.Parameters.Add(#Specialization, SqlDbType.VarChar,50).Value = this.specialization.Text;
command.Parameters.Add(#CountryName, SqlDbType.VarChar,50).Value = this.comboBox2.Text; //You should name this combo box
command.Parameters.Add(#Province, SqlDbType.VarChar,50).Value = this.comboBox4.Text; //You should name this combo box
command.Parameters.Add(#City, SqlDbType.VarChar,50).Value = this.comboBox3.Text;//You should name this combo box
}

Related

Inserting function in ASP.net is showing error and not executing the Insert query

Data comes from "Temp" table.
Stored in variables
Inserted into "Client" table with the addition of two more variables.
And there comes an error. The INSERT query is not executing properly.
Query,
int r;
string que = "INSERT INTO client (fname, lname, dob,
email, gender, uname, upass) VALUES
('" + fname + "',
'" + lname + "', '" + dob + "',
'" + email + "',
'" + gender + "',
'" + TextBox1.Text + "',
'" + TextBox2.Text + "') ";
r = c.savedeldata(que);
savedeldata Function
public int savedeldata(string qu)
{
con.Open();
cmd = new SqlCommand(qu, con);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
That's the only solution I can find.
if (ds.Tables["0"].Rows.Count == 1)
{
int r;
string queryt = "DELETE FROM tbl_client";
r = c.savedeldata(queryt);
string que = "INSERT INTO tbl_client(fname, lname, dob, email, gender) SELECT * FROM temp WHERE dob = '" + TextBox3.Text + "'";
r = c.savedeldata(que);
string quer = "UPDATE tbl_client SET uname = '"+ TextBox1.Text +"', upass = '"+ TextBox2.Text +"' WHERE dob = '"+ TextBox3.Text +"'";
r = c.savedeldata(quer);
}

OleDbException: Syntax error in INSERT INTO statement

I got OleDbException: Syntax error in INSERT INTO statement. I think that my INSERT INTO statement is good. Parameters have good data type so it's not problem. Does someone maybe know what's the problem?
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = String.Format("INSERT INTO Employees" +
" (ID, Company, Last Name, First Name, E-mail Address, Job Title, Business Phone, Home Phone" +
", Mobile Phone, Fax NUmber, Address, City, State/Province, ZIP/Postal Code, Country/Region, Web Page, Notes)" +
" Values ('{0}', '{1}','{2}','{3}','{4}','{5}'," +
"'{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')", iD,kompanija,prezime,ime,email,
zvanje,busTelefon,telefon,mobTelefon,fax,adresa,grad,okrug,postanskiBroj,zemlja,web,beleska); zvanje,busTelefon,telefon,mobTelefon,fax,adresa,grad,okrug,postanskiBroj,zemlja,web,beleska);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Error message:
UDATE SQL:
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
string cmdText = String.Format(#"UPDATE TABLE Employees " +
"SET" +
" Company='" + kompanija + "'," +
" [Last Name]='" + prezime + "'," +
" [First Name]='" + ime + "'," +
" [E-mail Address]='" + email + "' ," +
" [Job Title]='" + zvanje +"'," +
" [Business Phone]='" + busTelefon + "'," +
" [Home Phone]='" + telefon + "'," +
" [Mobile Phone]='" + mobTelefon + "'," +
" [Fax Number]='" + fax + "'," +
" Address='" + adresa + "'," +
" City='" + grad + "'," +
" [State/Province]='" + okrug + "'," +
" [ZIP/Postal Code]='" + postanskiBroj + "'," +
" [Country/Region]='" + zemlja + "'," +
" [Web Page]='" + web + "'," +
" Notes='" + beleska + "' WHERE ID="+iD);
command.CommandText = cmdText;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
And this SQL don't work. The same error like previous.
When your fields names contain a space or other misleadings characters like the / (division operator) you need them to be enclosed in square brackets
string cmdText = #"INSERT INTO Employees
(ID, Company, [Last Name], [First Name], [E-mail Address],
.., [State/Province], ....) VALUES (....)";
Also you are not using parameters in your query. String.Format is just another type of string concatenation that cannot protect you by invalid inputs (for example, try to use a single quote in your lastname value) and cannot save your code from Sql Injection vulnerability.
You should always use parameterized queries
string cmdText = #"INSERT INTO Employees ( your_field_list_comma_sep)
VALUES (#id, #company, #lastname, #firstname,
......)";
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.Parameters.Add("#id", OleDbType.Integer).Value = iD;
cmd.Parameters.Add("#company", OleDbType.VarWChar).Value = kompanija;
cmd.Parameters.Add("#lastname", OleDbType.VarWChar).Value = prezime;
cmd.Parameters.Add("#firstname", OleDbType.VarWChar).Value = ime;
....
// add all the other parameters with their name and type
....
cmd.ExecuteNonQuery();

Exception Inserting Image To MSAccess Database

Here I am inserting an image in msaccess database (accdb). I am not able to figure out why this is generating expcetion. It says Error in insert into statement.
String q = #"Insert Into tblModal (ModalName, CategoryId, Gender, Type, Description, image, LastUpdated) values ('" +
txtModalName.Text + "','" + categoryId + "','" + gender + "','"+txtType.Text +"', '" + txtDescription.Text + "',#pic, '" + DateTime.Now.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(q);
cmd.Parameters.AddWithValue("#pic", Check.imageToByteArray(pictureBoxPhoto.Image));
int res;
res = br.ExecuteNonQuery(cmd);

Update query issue C#

string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province'" + prov + "'where id='" + id + "'";
error :
System.Data.SqlClient.SqlException: Incorrect syntax
can anybody cor rectify the query ?
Your missing an equal:
"',province = '" + prov + "' where id='" + id + "'";
And do not build SQL-Queries like this. Please use ADO.Net Parameter.
Equal sign is missing:
,province='" + prov + "' where id='" + id + "'";
string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province='" + prov + "'where id='" + id + "'";
You miss = after province and there is no space between prov and where !
Also in this case you are open to SqlInjection, please use SqlCommand.Parameters.
The Query should look like this.
string sql = #"Update stdrecord set firstname=#FName ,lastname=#LastName, mobile=#Mobile,
phone=#Phone,city=#City, province=#Province where id=#ID";
This will protect you from SqlInjection and also sql server will cache your query.
To using command Parameters you need to add this code to your SqlCommand
SqlCommand cmd = new SqlCommand(sql, connectionString);
cmd.Parameters.AddWithValue("#FName", fName);
cmd.Parameters.AddWithValue("#LastName", lname );
cmd.Parameters.AddWithValue("#Mobile", mob);
cmd.Parameters.AddWithValue("#Phone", phn);
cmd.Parameters.AddWithValue("#City", city);
cmd.Parameters.AddWithValue("#Province", prov);
cmd.Parameters.AddWithValue("#ID", id);
With this structure you will not have problems like this in future because you will not add + and ' non stop. Also use # when you build string this give you the possibility to write string on more than one line without using +.
Put a space before Where Clause and equal sign in province column, will get work perfectly

Updating data in database using datagridview

i have a code like this:
public int updateFriend(long id, string Firstname, string Lastname, string Nickname, DateTime Birthdate, int Age, string Gender)
{
OleDbConnection con = new OleDbConnection(conString());
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
return (rowsAffected);
}
now the problem is when i click the update button it calls the method updateFriend, then an error appears on the Line "int rowsAffected = cmd.ExecuteNonQuery();" saying
"No value given for one or more required parameters."
Can somebody help me with this?
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
You are passing all parameters as string where some of them are int and one is DateTime. As suggested you should use Parameters.AddWithValue()
string query = "UPDATE FriendList SET Firstname = #Firstname, Lastname = #Lastname , Nickname = #Nickname, Birthday = #Birthdate, Age = #Age, Gender = #Gender WHERE ID = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Firstname", FirstName);
//add rest parameters the same way as above
cmd.Parameters.AddWithValue("#id", id);
Talking about on your error message;
"No value given for one or more required parameters."
This message will appears probably one of your parameters is null or zero-length string. Or the reason can be misspelling of your parameters.
Check your query in your database first and look which column gives you an error.
And please, never add your parameters in your sql command. That may cause SQL Injection attack. Always use parameterized query on your queries.
Check out SqlParameterCollection.AddWithValue() method from MSDN.

Categories