I'm trying to add something so that things can be deleted from a table, though it says there is a syntax error near '=' and I can't seem to spot it. I know this isn't the most ideal way to be doing this, but I've been told to do it this way.
Here's what I've put:
Con.Open();
string query = "DELETE FROM tablepassengers WHERE passportno.=" + tbpassno.Text + ';';
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
Con.Close();
populate();
As you said the . is meant to be there and that the column name is passportno., this is where your problem is. It's not something that is expected, or recommended, but it is something that can be handled.
When using Sql you really should be using Parameters when constructing Sql statements in code. It is strongly suggested, not only is it good practice it will protect your applications from targetted attacks, to use Parameters -- Please read Why do we always prefer using parameters in SQL statements?
Change your code to look like this:
string query = "DELETE FROM tablepassengers WHERE [passportno.]=#passportNo;";
using (SqlCommand cmd = new SqlCommand(query, Con))
{
cmd.Parameters.Add(new SqlParameter("passportNo", SqlDbType.VarChar, 100).Value = tbpassno.Text;
cmd.ExecuteNonQuery();
}
MessageBox.Show("deleted");
Con.Close();
try
{
string query = "DELETE FROM tablepassengers WHERE passportno=" + tbpassno.Text;
SqlCommand cmd = new SqlCommand(query, Con);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
}
catch (SqlException ex)
{
MessageBox.Show("Error\n" + ex.Message);
}
finally
{
Con.Close();
}
Related
I'm working on Form that sends about 9 fields to my SQL ACCESS database and i got this error.
"Data type mismatch in criteria expression."
i'm sure it's something with the ' x ' i put in my query but still can't figure out what is THE problem.
it's (int,int,string,string,string,int,int,string,int,int) format
string SqlStr = string.Format("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values({0},{1},'{2}','{3}','{4}',{5},{6},'{7}',{8},{9})", s.ClientId,s.OrderId,s.Date,s.CardTyp,s.PayMethod,s.Ex_Y,s.Ex_M,s.CcComp,s.CcNum,s.TotalSale);
Thanks for your help.
String.Format will not be a good approach for building queries. I suggest you to use, Parameterised queries that helps you to specify the type too and also its more helpful to prevent injection: Here is an example for you:
string query = "insert into Orders" +
"(client_id,order_id,date_,card_typ,...)" +
" values(#client_id,#order_id,#date_,#card_typ...)";
using (SqlCommand sqCmd = new SqlCommand(query, con))
{
con.Open();
sqCmd.Parameters.Add("#client_id", SqlDbType.Int).Value = s.ClientId;
sqCmd.Parameters.Add("#order_id", SqlDbType.VarChar).Value = s.OrderId;
sqCmd.Parameters.Add("#date_", SqlDbType.DateTime).Value = s.Date;
sqCmd.Parameters.Add("#card_typ", SqlDbType.Bit).Value = s.CardTyp;
// add rest of parameters
//Execute the commands here
}
Note: I have included only few columns in the example, you can replace ... with rest of columns.
Please dont use a concatenation string ...
Here is an example :
using (SqlConnection connection = new SqlConnection("...connection string ..."))
{
SqlCommand command = new SqlCommand("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values(#client_id,#order_id,#date_,#card_typ,#pay_mthd,#ex_y,#ex_m,#cc_comp,#cc_num,#t_sale)", connection);
SqlParameter pclient_id = new SqlParameter("#client_id", System.Data.SqlDbType.Int);
pclient_id.Value = 12;
command.Parameters.Add(pclient_id);
SqlParameter pcard_typ = new SqlParameter("#card_typ", System.Data.SqlDbType.VarChar);
pcard_typ.Value = "some value";
command.Parameters.Add(pcard_typ);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
This is my code for the insert, I got textboxes on my form and I write something inside but when pressing the button with executes the code below it shows an error by the (cmd.ExecuteNonQuery)
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype, patribute, role, role2, role3) VALUES (#Heroname, #Attacktype, #patribute, #role, #role2, #role3)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#Attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
textBox1.Clear(); textBox2.Clear();
textBox3.Clear(); textBox4.Clear();
textBox5.Clear(); textBox6.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
The second code snippet is my update code which shows same an error when trying to execute, same error by the execute non query
SqlDataReader reader = null;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
SqlCommand sda = new SqlCommand("SELECT * FROM Heroes ", cn);
cn.Open();
reader = sda.ExecuteReader();
while (reader.Read())
{
object Heroname = reader["heroname"];
listBox1.Items.Add(Heroname.ToString());
}
reader.Close();
cn.Close();
Please I need help and as quick as someone can, ty!
I think you receive this error, that because you using reserved word Role you should place It in brackets [].
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype,patribute,[role],role2,role3) VALUES (#Heroname, #Attacktype,#patribute,#role,#role2,#role3)";
I suggest to avoid that method of passing parameters, with
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
you didn't specify datatype and length, that's correct ADO.NET will guess them but this is not happens always, instead of that try this method:
cmd.Parameters.Add("#Heroname", SqlDbType.VarChar, 50).Value = textBox1.Text;
for all of your parameters.
Was it a null reference exception?
Reading your code, I think you need to change SqlDataReader reader = null; to SqlDataReader reader = new SqlDataReader;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
SqlCommand cmd = new SqlCommand("INSERT INTO Heroes (heroname,attacktype,patribute,role,role2,role3) Values (#heroname,#attacktype,#patribute,#role,#role2,#role3) ", cn);
cn.Open();
cmd.Parameters.AddWithValue("#heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
This code worked now, inside my form i added a listbox and it does show the added row with its values! But closing form and checking inside database, it doesnt show that row? Whats wrong?
private void DeleteQuestion_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection conn = new OleDbConnection(access7ConnectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("DELETE FROM Questions" + "WHERE ID=#ID", conn))
{
cmd.Parameters.AddWithValue("#ID", currentRecord);
cmd.ExecuteNonQuery();
}
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.ToString());
}
}
I get this error:
Syntax in FROM Clause
Where am I going wrong? Still learning C#
access7ConnectionString is a string path to the database, I've cut it out to shorten down the post, but the connection to the database is established and it all works.
There is no space between Table Name and WHERE, Place a space like:
"DELETE FROM Questions" + " WHERE
///^^^
Not really sure why you have to use string concatenation. It all can be par to of a single string. like:
using (OleDbCommand cmd = new OleDbCommand("DELETE FROM Questions WHERE ID=#ID", conn))
You are missing a space, change
"DELETE FROM Questions" + "WHERE ID=#ID"
to
"DELETE FROM Questions WHERE ID=#ID"
con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO user(Firstname,Lastname,Email,Pass,Type)
values(#first,#last,#email,#pass,#type)",con);
cmd.Parameters.Add("#first",SqlDbType.NVarChar).Value = txtfirst.Text;
cmd.Parameters.Add("#last",SqlDbType.NVarChar).Value = txtlast.Text;
cmd.Parameters.Add("#email",SqlDbType.NVarChar).Value = txtemail.Text;
cmd.Parameters.Add("#pass",SqlDbType.NVarChar).Value = txtpass.Text;
cmd.Parameters.Add("#type",SqlDbType.NVarChar).Value = "customer";
cmd.ExecuteNonQuery();
con.Close();
what is the problem with my syntax it says "Incorrect syntax near the keyword 'user'."
you should escape the table name user with delimited identifiers,
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(#first,#last,#email,#pass,#type)",con);
SQL Server Reserved Keywords
SQL Server Delimited Identifiers
UPDATE 1
Refractor your code by
using using statement to properly dispose objects
using Try-Catch block to properly handle exceptions
code snippet:
string _connStr = "connectionString here";
string _query = "INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values (#first,#last,#email,#pass,#type)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#first", txtfirst.Text);
comm.Parameters.AddWithValue("#last", txtlast.Text);
comm.Parameters.AddWithValue("#email", txtemail.Text);
comm.Parameters.AddWithValue("#pass", txtpass.Text);
comm.Parameters.AddWithValue("#type", "customer");
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(SqlException ex)
{
// other codes here
// do something with the exception
// don't swallow it.
}
}
}
AddWithValue
Add (recommended one)
USER is a reserved keyword on SQL Server.
You should use your table name with brackets [] like;
INSERT INTO [user]
You can try like;
con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(#first,#last,#email,#pass,#type)",con);
cmd.Parameters.AddWithValue("#first", txtfirst.Text);
cmd.Parameters.AddWithValue("#last", txtlast.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#pass", txtpass.Text);
cmd.Parameters.AddWithValue("#type", "customer");
cmd.ExecuteNonQuery();
con.Close();
And also like #JW said, it is always a good approach to using them in a try-catch statement.
Best Practices of Exception Management
In my code neither of these queries appear to be running. The debug label is printing as "end" so it is executing something inside that code block, just appears it doesn't like the queries?
// Check input is all valid
if (Page.IsValid)
{
debug.Text = "begin";
using (SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand(
"UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO tblSiteSettings (allowProductRatings, allowComments, " +
"siteName, settingDate, isActive) VALUES (#allowRatings, " +
"#allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cn.Close();
}
debug.Text = "end";
}
}
A few questions:
Why are they not executing?
In classic ASP for inserts, updates and deletes I would use con.Execute(query) as supposed to using a recordset, am I running my update statement correctly here?
Is my design of the queries good, or should I be executing them in a different manner?
The reason it's not doing anything is because you're not actually executing the queries. What you need to do is:
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblSiteSettings (allowProductRatings, allowComments, siteName, settingDate, isActive) VALUES (#allowRatings, #allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
It's the line cmd.ExecuteNoneQuery(); that you're missing. There are various different Execute methods exposed by the SqlCommand class, the most commonly used are:
ExecuteNonQuery: Executes a query and returns no result from the query (it does return the rows affected as its return value however)
ExecuteScalar: Executes a query and returns the value in the first column of the first row
ExecuteReader: Executes a query and returns the data to a SqlDataReader
Your are missing
cmd.ExecuteScalar();
You may also reuse you SqlConnection, you can open the connection right after the using (SqlConnection cn = new Sql... statement. You don't have to close the connection when the SqlConnection is in a using block, accordning to the documentation the connection is closed when you are leaving the using block.