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

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

Related

Upload CSV File In C# [duplicate]

This question already has an answer here:
ORA-00936 missing expression
(1 answer)
Closed 3 years ago.
I have got problem when I try to upload my csv file into Oracle Database in C#. The error message occured like this {"ORA-00936: missing expression"}. I have no idea to fix it. Does anyone here could help me to solve this problem please.
This is my current code;
conn.Open();
foreach(DataRow importRow in importData.Rows)
{
OracleCommand cmd = new OracleCommand("INSERT INTO TMCI_PPC_IMPORTDATA_PSI (ITEM, REQUIREMENT, REQ_DATE)" +
"VALUES (#Itm, #Req, #ReqDT)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Itm", importRow["ITEM"]);
cmd.Parameters.Add("#Req", importRow["REQUIREMENT"]);
cmd.Parameters.Add("#ReqDT", importRow["REQ_DATE"]);
cmd.ExecuteNonQuery();
}
Several issues:
Oracle uses :, not # for parameters
You should create parameters once, before loop.
Code:
...
conn.Open();
// Oracle uses : not # for parameters
string query =
#"INSERT INTO TMCI_PPC_IMPORTDATA_PSI (
ITEM,
REQUIREMENT,
REQ_DATE)
VALUES (
:Itm,
:Req,
:ReqDT)";
//DONE: wrap IDisposable into using
using (OracleCommand cmd = new OracleCommand(query, conn)) {
//DONE: create parameters once
//TODO: validate parameters' types
cmd.Parameters.Add(":Itm", OracleDbType.Varchar2);
cmd.Parameters.Add(":Req", OracleDbType.Varchar2);
cmd.Parameters.Add(":ReqDT", OracleDbType.Date);
foreach(DataRow importRow in importData.Rows) {
// assign parameters as many as you want
cmd.Parameters[":Itm"].Value = importRow["ITEM"];
cmd.Parameters[":Req"].Value = importRow["REQUIREMENT"];
cmd.Parameters[":ReqDT"].Value = importRow["REQUIREMENT"];
cmd.ExecuteNonQuery();
}
}
I am pretty sure the parameters need to have : as a prefix not #
OracleCommand cmd = new OracleCommand("INSERT INTO TMCI_PPC_IMPORTDATA_PSI (ITEM, REQUIREMENT, REQ_DATE)" +
"VALUES (:Itm, :Req, :ReqDT)", conn);
And change your paramters to be like the following:
command.Parameters.Add(new OracleParameter("Itm", importRow["ITEM"]);

Data type mismatch in criteria expression - started only recently

I use Access database. This error wasn't occurring 30 minutes ago.
ERROR is:
Data type mismatch in criteria expression.
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid)
values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
My database columns are:
ID = AutoNumber
isin_adi = Short Text
isin_tanimi = Long Text
verildigi_tarih= Date/Time
teslim_tarihi=Date/Time
sorumlu_marka = Short Text
sorumlu_ajans=Short Text
personel_id=Number
revize=Short Text
is_durum=Short Text
Temsilci_isverenid=Number
I Solved the problem. I realized the rank of parameters was not true. i change my code like that:
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid) values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
after that i get error like this :
You cannot add or change a record because a related record is required in table 'Personel'.
And i remove the relationship from 2 tables. And now it works normally.
I think access database have some bugs ,and even if code is correct, errors may accuired.
So i will move my database to SQL from ACCESS i think. Thanks guys.

Cannot insert value via SqlDataAdapter

I am learning how to work with SQL in C#, and I got in troubles with using SqlDataAdapter. I have tried to use direct queries via SqlCommand class and everything works fine, but when I rewrote my code to use SqlDataAdapter I have no changes in my table. There is my code:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ADO"]
.ConnectionString);
connection.Open();
SqlDataAdapter daUser = new SqlDataAdapter("SELECT * FROM Books", connection);
SqlCommand insert = new SqlCommand();
insert.Connection = connection;
insert.CommandText = "INSERT INTO Books (name, author) VALUES (#name, #author);";
SqlParameterCollection pc = insert.Parameters;
pc.Add("#name", SqlDbType.VarChar, 20, "test123");
pc.Add("#author", SqlDbType.VarChar, 20, "test322");
daUser.InsertCommand = insert;
DataSet ds = new DataSet();
daUser.Fill(ds, "Books");
daUser.Update(ds, "Books");
Table Books was created with this SQL query in SQL Server Management Studio:
CREATE TABLE Books
(
id int PRIMARY KEY IDENTITY(1,1),
name varchar(MAX) NOT NULL,
author varchar(MAX) NOT NULL
)
INSERT INTO Books(name, author)
VALUES('1984', 'George Orwell'), ('Fathers and sons', 'Dostoevski')
Looks like I am missing something to do, that why my code have no effect on table.
SqlDataAdapter.Update will call its InsertCommand only for the rows of datatable having RowState = DataRowState.Added.
This rowstate is automatically assigned to the datarows being added to rows collection using DataTable.Add method (until next call to AcceptChanges method). Also you can use DataRow.SetAdded method to force this state assignment.
Since you're not modifying/adding anything in you datatable after you've populated it with select command, it has nothing to insert.
Change your code to something like
daUser.Fill(ds, "Books");
var newBook = daUser.Tables[0].NewRow();
newBook["name"] = "New Book";
newBook["author"] = "Author Name";
daUser.Tables[0].Rows.Add(newBook);
daUser.Update(ds, "Books");
and in this case it should be new row added to the database table.
See MSDN for reference.
Just to clarify the previous answer, which is correct, you want to call ExecuteNonQuery() on the command not the dataAdapter.
SqlCommand insert = new SqlCommand();
insert.Connection = connection;
insert.CommandText = "INSERT INTO Books (name, author) VALUES (#name,
#author);";
SqlParameterCollection pc = insert.Parameters;
pc.Add("#name", SqlDbType.VarChar, 20, "test123");
pc.Add("#author",
SqlDbType.VarChar, 20, "test322");
// you do not need this line if you execute the insert on the command object.
// daUser.InsertCommand = insert;
//Add this line instead:
insert.ExecuteNonQuery();
Joey

How to update MySql table row through C# console application?

I am writing a console application and fetch data from MySql table .
Code :
string connection = "Server=localhoht;Database=data;Uid=root;Pwd=root123";
MySqlConnection dbcon = new MySqlConnection(connection);
MySqlCommand selectData;
dbcon.Open();
selectData = dbcon.CreateCommand();
selectData.CommandText = "SELECT user_id, user_name,user_type FROM win_user WHERE user_type=1 ORDER BY user_id ASC ";
MySqlDataReader juh = selectData.ExecuteReader();
And its working fine. Now I want to update a row with the code below :
string updatedata = "UPDATE win_user SET user_type='1' WHERE user_id= '1'";
MySqlDataAdapter MyData = new MySqlDataAdapter();
MyData.UpdateCommand = new MySqlCommand(updatedata, dbcon);
But its not working.
You can run the commend "UPDATE win_user SET user_type='1' WHERE user_id= '1'" in any sql client tools, eg, navicat, to verify wheather it's correct on your mysql database.
The MySqlDataAdapter could be used to update rows in a database table using the Update method.
The Update method (link is for SqlServer but the concept is the same) has many overload, but basically it requires a DataTable with rows modified in some way ([RowState != DataRowState.Unchanged][2]) so the MySqlDataAdapter can pick the rows changed and apply the DeleteCommand, UpdateCommand and InsertCommand defined in the adapter
Your code above doesn't shown any kind of interaction with a datatable and you have a call to the Update method so there is no way for the update to occur.
You could, of course execute directly your command without any adapter involved
EDITed to change every user_type not 1 to 1
string updatedata = "UPDATE win_user SET user_type=1 WHERE user_type <> 1";
MySqlCommand cmd = new MySqlCommand(updatedata, dbcon);
int numOfRowsChanged = cmd.ExecuteNonQuery();

Deleting records from a table, is this correct?

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.

Categories