Deleting records from a table, is this correct? - c#

I want to delete some record from table ,by running this Query in C# is it Correct or not,
Please help me
SqlCommand cmdRe = new SqlCommand("insert into msisdn_master SELECT * from tblDeactive
where msisdn in (" + str_MSISDN + ")", cn);
SqlCommand cmdRed = new SqlCommand("delete from tblDeactive where msisdn in ("+str_MSISDN+")", cn);
cmdRe.CommandType = CommandType.Text;
cmdRed.CommandType = CommandType.Text;
note : str_MSISDN is the StringBuilder which stores the Number which is inserted in TextField.

You should be using proper SQL parameters. NEVER use string building since that leaves you open for injection attacks.
Read this tutorial to learn how to add parameters to SqlCommands.

Related

I cannot insert anything but "Id" values into tables [duplicate]

This question already has answers here:
What are good ways to prevent SQL injection? [duplicate]
(4 answers)
Closed 3 years ago.
I am currently building my first web app from scratch and trying to figure out the communication of C# and SQLDatabases, I've been trying to enter custom data into a table.
This code for some reason works perfectly fine, and it successfully adds "Id = 3" in a new row:
sql = " INSERT INTO dbo.AspNetUsers (Id) VALUES (3)";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
But this one does not, and the only difference is that it adds another item in a different column, as opposed to the previous one which it only adds the "Id":
sql = " INSERT INTO dbo.AspNetUsers (Id, UserName) VALUES (3, testName)";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
Lastly, another problem I have, I am unable to use either ExecuteReader() and ExecuteScalar() to read data from tables created by me as opposed the ones set up by the Framework auth system.
Thanks in advance.
This code addresses both issues:
the value of UserName is passed as a SQL parameter, which is recommended for string values to avoid SQL injection and other possible problems,
the SQL command is executed with ExecuteNonQuery, the correct way of calling SQL commands that do not return any result
SqlCommand cmd = new SqlCommand();
string sql = " INSERT INTO dbo.AspNetUsers (Id, UserName) VALUES (3, #testName)";
cmd.Parameters.AddWithValue("#testName", "testName");
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();

Insert Textbox.text "123456" as password in Mysql database

I want to create a User and Insert to an exist table with a mysql query.
I have this in C#:
using (OdbcCommand cmd6 = new OdbcCommand("INSERT INTO users (id,Name,login,pass) VALUES ('" + textboxID.Text + "','" + textboxNAME.Text + textboxLOGIN.Text + "','" + textboxPASS.Text + "' )", conn6))
I want to get the pass from textboxPASS.Text and inserts as encrypted, because now it inserts as text.
Note.-
If I put "pass123456" in my textboxPASS...It take it and inserts as text: "pass123456".
And when I see the table, the others already existing users have encrypted passwords. (around 40 numeric characters).
But my new user has that field as text "pass123456".
I hope you can help me.
Thanks!
The SQL is doing what it is told. If you want to run some cryptographic operation on the data first, you must do that:
// note using ? since ODBC has poor support for named parameters, IIRC
using (OdbcCommand cmd = new OdbcCommand(
"INSERT INTO users (id,Name,login,pass) VALUES (?,?,?,?)", conn))
{
// this is most likely a hash op, and probably involves salt of some kind
var cryptoPass = SomeCryptoOperation(..., textboxPASS.Text);
cmd.Parameters.AddWithValue("id", textboxID.Text);
cmd.Parameters.AddWithValue("name", textboxNAME.Text);
cmd.Parameters.AddWithValue("login", textboxLOGIN.Text);
cmd.Parameters.AddWithValue("pass", cryptoPass);
cmd.ExecuteNonQuery();
}
Just call the encrypt function eg.
using (SqlCommand cmd6 = new SqlCommand("INSERT INTO Users VALUES(#Username, #Password)"))
{
cmd6.CommandType = CommandType.Text;
cmd6.Parameters.AddWithValue("#Username", txtUsername.Text.Trim());
cmd6.Parameters.AddWithValue("#Password", Encrypt(txtPassword.Text.Trim()));
for more advanced encryption check for AES functions

Syntax error while trying to fetch data from MySql

So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.

How to initialize Access Number field in C-Sharp

I know how to use Text Box value in Access query for string fields, but i am unable to understand how to use it for int fields.
I am writing the following query and receiving error messages.
ERROR MESSAGE: No value given for one or more required parameters.
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " +textBox2.Text , conn);
conn.Open();
cmd.ExecuteNonQuery();
I also tried to convert textBox2 into int, but its also given me an error message.
Input string was not in a correct format.
int Id= Convert.ToInt16(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " + Id , conn);
conn.Open();
cmd.ExecuteNonQuery();
This answer corrects your problem
First, the TextBox for Name is not the same Textbox used for ID
Second, do not concatenate strings to build sql commands. It is very error prone and open to a well know sql vulnerability called Sql Injection
string queryText = Update Table1 Set Name= ? where ID= ?";
OleDbCommand cmd = new OleDbCommand(queryText, conn);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", Convert.ToInt32(TextBox2.Text));
conn.Open();
cmd.ExecuteNonQuery();
Here I have removed the string concatenation and inserted two parameters placeholders (?),
then I have added to the OleDbCommand two parameters and their values.
When executing the query the OleDb code will replace the placeholders with the actual values checking for invalid characters and invalid sql statements

OleDbDataAdapter Update To dbf [Free Table] -Syntax Error()

When I insert through the OleDbCommand with direct values no problem, it's working fine
OleDbCommand OleCmd1 = new OleDbCommand("Insert into My_Diary (sl_no,reminder) values("+a1+",'CHECK VALUE')", OleCon1);
OleCmd1->ExecuteNonQuery();
But when I like to update through parameter its showing "Syntax Error"....I can't identify my mistake...
string MyConStr = "Provider=VFPOLEDB.1; Data Source='C:\\For_Dbf'; Persist Security Info=False";
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (#sl_no,#reminder) ";
VFPDAp=gcnew OleDbDataAdapter();
VFPDApMy_Table1InsertCommand = gcnew OleDbCommand(InsSavDiaryCmd, OleCon1);
WithInsVar = VFPDAp.InsertCommand.Parameters;
WithInsVar.Add("#sl_no", OleDbType.Integer, 10, "sl_no");
WithInsVar.Add("#reminder", OleDbType.Char, 250, "reminder");
OleCon1.ConnectionString = MyConStr;
OleCon1.Open();
OleDbTransaction Trans=OleCon1.BeginTransaction();
//VFPDAp.DeleteCommand.Transaction = Trans;
//VFPDAp.UpdateCommand.Transaction = Trans;
VFPDAp.InsertCommand.Transaction = Trans;
VFPDAp.Update(MyDataTbl);
Trans.Commit();
OleCon1.Close();
The OleDbCommand doesn't use named parameters. You need to change the insert statement so that it uses questions.
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (?, ?) ";
You need to make sure that you have a parameter for each question mark and make sure that the parameters are inserted in order of their use in the insert statement.
** If you'd like to use name parameters... you can try using VfpClient which is a project that I'm working on to make data access a little nicer from .Net.

Categories