Saving data depending on the text contained in another column - c#

SQL1 portion works just fine, but I need help figuring out if my statements in SQL2, 3 & 4 are correct because it currently doesn't work. I want to insert 'Audience View 1' in VIEW if the words 'Camera 1' is present in VIDEOPATH, 'Audience View 2' in VIEW if the words 'Camera 2' is present in VIDEOPATH and so on.
string[] files = Directory.GetFiles("C:/Users/sit/Videos/Done/");
string view1 = "Audience View 1";
string view2 = "Audience View 2";
string view3 = "Lecturer View";
foreach (string file in files) {
string SQL1 = "INSERT INTO TBL_LESSONCAM(VIDEOPATH)VALUES('" + (file) + "')";
string SQL2 = "UPDATE TBL_LESSONCAM(VIEW)VALUES('" + (view1) + "')" + "WHERE VIDEOPATH LIKE '%Camera 1%'";
string SQL3 = "UPDATE TBL_LESSONCAM(VIEW)VALUES('" + (view2) + "')" + "WHERE VIDEOPATH LIKE '%Camera 2%'";
string SQL4 = "UPDATE TBL_LESSONCAM(VIEW)VALUES('" + (view3) + "')" + "WHERE VIDEOPATH LIKE '%Camera 3%'";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = SQL1;
cmd.CommandText = SQL2;
cmd.CommandText = SQL3;
cmd.CommandText = SQL4;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
UPDATE: Is my structure for running multiple SQL statements correct?

your update:
string SQL2 = "UPDATE TBL_LESSONCAM(VIEW)VALUES('" + (view1) + "')" + "WHERE VIDEOPATH LIKE '%Camera 1%'";
should be
string SQL2 = "UPDATE TBL_LESSONCAM set view = '" + (view1) + "'" + " WHERE VIDEOPATH LIKE '%Camera 1%'; ";
Please have a look at What are good ways to prevent SQL injection?

Related

Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}

c# SQL Error - Must declare scalar

I have declared the scalar already but I am still getting the error. My code checks to see if an entry exists, if it does it updates the entry or if it does not exist it creates a new entry:
try
{
string server = Properties.Settings.Default.SQLServer;
string connection = "Data Source=" + server + ";Initial Catalog=Propsys;Persist Security Info=True;User ID=sa;Password=0925greg";
using (SqlConnection cn = new SqlConnection(connection))
{
cn.Open();
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #" + this.contactPersonTextBox.Text, cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
SqlDataReader myReader;
myReader = cmdCount.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count > 0)
{
string query = "UPDATE _1Agent SET DealID = #DealID, \n" +
"ContactPerson = #ContactPerson, \n" +
"Address = #Address, \n" +
"TaxVatNo = #TaxVatNo, \n" +
"Comm = #Comm, \n" +
"WorkTel = #WorkTel, \n" +
"Cell = #Cell, \n" +
"Fax = #Fax, \n" +
"Email = #Email, \n" +
"Web = #Web, \n" +
"CreateDate = #CreateDate, \n" +
"Notes = #Notes WHERE id = #id";
SqlCommand cm = new SqlCommand(query);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
else
{
string query1 = "INSERT INTO _1Agent (DealID, \n" +
"ContactPerson, \n" +
"Address, \n" +
"TaxVatNo, \n" +
"Comm, \n" +
"WorkTel, \n" +
"Cell, \n" +
"Fax, \n" +
"Email, \n" +
"CreateDate, \n" +
"Notes) VALUES ('" + txtDealNo.Text + "',\n" +
"'" + contactPersonTextBox.Text + "',\n" +
"'" + addressTextBox.Text + "',\n" +
"'" + taxVatNoTextBox.Text + "',\n" +
"'" + commTextBox.Text + "',\n" +
"'" + workTelTextBox.Text + "',\n" +
"'" + cellTextBox.Text + "',\n" +
"'" + faxTextBox.Text + "',\n" +
"'" + emailTextBox.Text + "',\n" +
"'" + notesTextBox.Text + "',\n" +
"'" + DateTime.Now + "')";
SqlCommand cm = new SqlCommand(query1);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query1;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Your usage of parameter is wrong, it should be:
SqlCommand cmdCount =
new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
Later you are adding the parameter correctly.
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
To get the count use SqlCommand.ExecuteScalar, instead of using DataReader:
int count = (int) cmdCount.ExecuteScalar();
For the other queries, UPDATE and INSERT, you can use a verbatim string, instead of concatenating strings over multiple lines.
string query = #"UPDATE _1Agent SET DealID = #DealID,
ContactPerson = #ContactPerson,
Address = #Address,
TaxVatNo = #TaxVatNo,
Comm = #Comm,
WorkTel = #WorkTel,
Cell = #Cell,
Fax = #Fax,
Email = #Email,
Web = #Web,
CreateDate = #CreateDate,
Notes = #Notes WHERE id = #id";
Other issues with the code:
You are concatenating strings to form INSERT query, later you are adding parameters, follow the same convention as UPDATE query and then use the parameters.
As pointed out in the other answer, you are not adding parameter#id value for UPDATE command
You are not specifying connection property with your UPDATE and INSERT command:
Specify it like
SqlCommand cm = new SqlCommand(query, cn);
Consider enclosing Connection and Command object in using
statement as it will ensure the proper disposal of unmanaged resources.
I see a few things;
Don't use string concatenation with # sign for parameters. That's wrong usage. Use it like;
"SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson"
and
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
and use ExecuteScalar to get first column of the first row. Using a reader is unnecessary for this command.
Your UPDATE query requires #id value since you declare it in your command as;
cm.Parameters.AddWithValue("#id", yourIDvalue);
Your INSERT query, you never declare your parameters in your command. You just concatenate them with their values. And use verbatim string literal to generate multiline strings instead of using \n.
Please
Read more carefully about parameterized queries and how you can use them.
Give me parameterized SQL, or give me death
You forget to mention parameter name in your select query
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
There are some wrong things .So you can refer #Soner Gönül and #habib answers
And change your insert query.Since you have declared paramertes but you didn't define.So change as follows
string query1 = "INSERT INTO _1Agent (DealID,ContactPerson,Address,TaxVatNo,
Comm, WorkTel, Cell, Fax, Email,Notes,CreateDate)
VALUES ( #DealID , #ContactPerson,#Address ,#TaxVatNo ,
#Comm,#WorkTel , #Cell,#Fax,#Email,#Notes,#CreateDate)";

SQL query for update statement in (C#)

I am new to the C# programming. Facing the problem Incorrect syntax near 'First_Name'.! in the given below code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=HP\SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name ='" + fname.Text + "'");
//'" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("You Have Successfully Updated");
Custid.Text = "";
fname.Text = "";
lname.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
landmark.Text = "";
deposite.Text = "";
}
}
}
Problem : You forgot to add word SET after your table name in update statement.
Solution1 : Add the word SET after table name in Update query (Don't Recommend this)
"update Customer_Info SET First_Name ='" + fname.Text + "'"
Warning : Your query is open to sql injection attacks.please use parameterised queries to avoid them
Solution 2: Using Parameterised Queries
Replace This:
SqlCommand cmd = new SqlCommand("update Customer_Info SET First_Name
='"+fname.Text+"'");
With This:
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name = #fname");
cmd.Parameters.AddWithValue("#fname" , fname.Text);
Your problem not in C#, in SQL syntax (you miss set keyword)
SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");
you are missing SET keyword:
update Customer_Info SET First_Name ='" + fname.Text + "'"
and also provide where clause otherwise it will update all the records in your table.
You are missing set keyword in query you have to place set like this
SqlCommand cmd = new SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");

my update c# code is not working,can i update two relational table at once?

i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here

What is wrong whith my sql command?

I've tried this for several hours but I cannot figure it our what's wrong
var cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = mySqlConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"select Calle.Id_Calle FROM" +
"TominPredial.Calle as Calle,"+
"TominPredial.Colonia as Col," +
"TominPredial.Poblacion as Pob" +
"WHERE Calle.Nombre = #NombreCalle" +
"and Col.Id_Colonia = #id_col and Pob.Id_Poblacion = #id_pob";
cmd.Parameters.Add("#NombreCalle", nombreCalle);
cmd.Parameters.Add("#id_col", id_col);
cmd.Parameters.Add("#id_pob", id_pob);
cmd.ExecuteScalar()
It says incorrect syntax near "Calle"
There is no space between the lines:
"select Calle.Id_Calle FROM" +
"TominPredial.Calle as Calle,"+
"TominPredial.Colonia as Col," +
"TominPredial.Poblacion as Pob" +
"WHERE Calle.Nombre = #NombreCalle" +
"and Col.Id_Colonia = #id_col and Pob.Id_Poblacion = #id_pob";
This will make the query ... FROMTominpredial.calle ... pobWHERE .. which will generate a syntax error.
You have to put spaces between the keywords in the end of the lines. Something like so:
...
"select Calle.Id_Calle FROM" +
" TominPredial.Calle as Calle,"+
" TominPredial.Colonia as Col," +
" TominPredial.Poblacion as Pob" +
" WHERE Calle.Nombre = #NombreCalle" +
" and Col.Id_Colonia = #id_col and Pob.Id_Poblacion = #id_pob";
/\
put a Spaces here

Categories