Oracle parameterized update query c# - sql

It should work but it doesn't.
I have referred others but couldn't find the reason.
OracleCommand cmd = con.CreateCommand();
var query = $#"UPDATE Customer SET ContactName = :ct WHERE CustomerID = :id";
cmd.CommandText = query;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":id", OracleDbType.Varchar2, "bbb1", System.Data.ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter(":ct", OracleDbType.Varchar2, "Joon", System.Data.ParameterDirection.Input));
var rst = cmd.ExecuteNonQuery();
Thanks in advance.
Joon

I found why it didn't update table.
To make it work I added parameters in the order of the query parameter and found it works. But I still do not understand why the order of adding parameters is so important to make it work.But the thing clear is that it is working when I make it like this:
OracleCommand cmd = con.CreateCommand();
var query = $#"UPDATE Customer SET ContactName = :ct WHERE CustomerID = :id";
cmd.CommandText = query;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":ct", OracleDbType.Varchar2, "Joon", System.Data.ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter(":id", OracleDbType.Varchar2, "bbb1", System.Data.ParameterDirection.Input));
var rst = cmd.ExecuteNonQuery();
Thanks everybody who paid attention on it.
Joon

In order to avoid the order declaration, you can use BindByName:
OracleCommand cmd = con.CreateCommand();
cmd.BindByName = true; // Just add this
...

Related

ExecuteNonQuery returning a 0?

I have the following code that is comparing a hash value and username to the corresponding hash value and username in a local database (App_Users3)
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT Username, Hash FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
// savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value = savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show(" Query successful.. something matched.. ");
// change page.. load a profile?
}
It doesn't throw any errors but I don't understand why the messagebox isn't showing up.
ExecuteNonQuery returns the rows affected by modifying data statements (insert, update, delete). You should use ExecuteScalar for such select statements, and for example return the user's ID value. If you want to return more than one value (either multiple rows or multiple columns), you should use ExecuteReader.
Here is your code modified to return UserID of the matched user.
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT UserId FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
//savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value= savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteScalar() != null) {
MessageBox.Show(" Query successful..something matched.. ");
//change page.. load a profile?
}
}

Unable to convert object of type 'System.Data.SqlClient.SqlDataReader' to type 'System.IConvertible'

I am facing this error while i was trying to convert the session object type to int, I need to use that value in another query which is of datatype int.
SqlConnection sqlConnection1 = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=DESKTOP-59SGH72\\SQLEXPRESS;Trusted_Connection=True;Database=sport");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "select user_id from users where user_name='" + Session["usern"] + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
Session["userid"] = reader;
var uid = Convert.ToInt16(Session["userid"]);
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Please help me with this error !!
first of all your code is terrible -- it is totally going to get hacked by an injection attack. You should be using a parameterized query.
as to your question, something like this would work but you really should be doing lots of error checking and sanity checks:
reader = cmd.ExecuteReader();
reader.Read();
Session["userid"] = reader[0];
You probably should have looked at the documentation which has some nice examples
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx

"SQL0404: request value for TYPE is too long." error when using parameters

I have a query error with this parameter command. It seems that .NET in the parameter adds extra characters like `vbCrlf. If I try without parameter the update works.
Code:
Dim con As OleDbConnection
Dim txt_tip As String
txt_tip = DataGridView1.Rows(i).Cells(0).Value.ToString(0)
conn.ConnectionString = "Provider=IBMDA400;Data Source=172.xx.xx.xx;User Id=user;Password=pwd;"
con = New OleDbConnection(conn.ConnectionString)
con.Open()
Using updCommand As New OleDbCommand("UPDATE $Customers SET TYPE=#type, Name='Rob', Surname='Red', Desc='Test10' WHERE ID=100", con)
updCommand.Parameters.Add("#type", OleDbType.VarChar, 1).Value = txt_tip
updCommand.ExecuteNonQuery()
End Using
If I try it without the parameters the query works fine:
"UPDATE $Customers SET TYPE='1', Name='Rob', Surname='Red', Desc='Test10' WHERE ID=100"
The server is IBM AS400.
OP posted answer in comments
Instead of of specifying a name for the parameter use a ? as a placeholder:
Using updCommand As New OleDbCommand("UPDATE $Customers SET TYPE=?, Name='Rob', Surname='Red', Desc='Test10' WHERE ID=100", con)
updCommand.Parameters.Add("?", OleDbType.Char).Value = txt_tip
...
End Using
If you want to add more just ensure the order is correct:
Using updCommand As New OleDbCommand("UPDATE $Customers SET TYPE=?, Name=?, Surname=?, Desc='Test10' WHERE ID=100", con)
updCommand.Parameters.Add("?", OleDbType.Char).Value = txt_tip
updCommand.Parameters.Add("?", OleDbType.VarChar).Value = "Rob"
updCommand.Parameters.Add("?", OleDbType.VarChar).Value = "Red"
...
End Using

strange workflow in ado.net with vb.net

i had assigned a job for insert,update, delete operation in a table for my student. he had done this assignment fine. but his code is made me crazy that he wrote update code like below
Working sample:
Public Function Toeditdetails(ByVal item As Boolean)
If item = True Then
Dim con As SqlConnection
'Dim retval As Integer
con = New SqlConnection(conn)
con.Open()
Dim cmd As SqlCommand
cmd = New SqlCommand("updatelogin", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("#username", SqlDbType.VarChar, 100)).Value() = TextBox1.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#user_password", SqlDbType.VarChar, 30)).Value() = TextBox2.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#nameofuser", SqlDbType.VarChar, 100)).Value() = TextBox3.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#contact_no", SqlDbType.VarChar, 10)).Value() = TextBox4.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#email", SqlDbType.VarChar, 100)).Value() = TextBox5.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#joiningdate", SqlDbType.Date)).Value() = DateTimePicker1.Value
cmd.Parameters.Add(New SqlParameter("#usergroup_id", SqlDbType.Int)).Value() = SelectedID(ComboBox1.Text)
If item = True Then
cmd.Parameters.Add(New SqlParameter("#id", SqlDbType.Int)).Value() = Label9.Text.Trim()
End If
Dim da As SqlDataAdapter
da = New SqlDataAdapter(cmd)
Dim dst As New DataSet
da.Fill(dst)
If dst.Tables.Count > 0 Then
DataGridView1.DataSource = dst.Tables(0)
End If
If Not cmd Is Nothing Then
cmd.Dispose()
End If
End If
End Function
Note there is no ExecuteNonQuery() method for his SqlCommand object and he didn't call this method in entire project. when i call function result still updating... how its happen? anyone genius can you explain whats going on above statement? any help would be appreciated
Regards and thanks
Sarva
when you call Toeditdetails method it will execute stored procedure called updatelogin
check the stored procedure and you may able to find why you receive updated result. Stored procedure several statements like below
update table1 set username ='test1' where uid =#uid;
select * from table1;
when you call stored procedure with above code you will get the table1 data but update statement will update data before you receive it.

How to pass integer variable in sql query

int no = FormView1.PageIndex;
Query:-
SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
You have to add a parameter:
int no = FormView1.PageIndex;
SqlCommand cmd =
new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
// Set the parameter up before executing the command
cmd.Parameters.Add("#no", SqlDbType.Int);
cmd.Parameters["#no"].Value = no;
You need to add a SqlParameter to the SqlCommand:
int no = FormView1.PageIndex;
SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
cmd.Parameters.AddWithValue("#no", no);
use an array of System.Data.SqlClient.SqlParameter
SqlCommand cmd(...);
SqlParameter[] inQueryParameters = ...;
cmd.Parameters.AddRange(inQueryParameters);
Use SqlParameters. See the example below.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
You can use this code:
SqlCommand ageCom = new SqlCommand("select age_phase from PatintInfo where patient_ID=#ptn_id", con);
ageCom.Parameters.Add("#ptn_id",SqlDbType.Int).Value=Convert.ToInt32(TextBox1.Text);
It had worked in my program correctly.