Get value instead of whole query - c#

I want to get the value of the Encrypted password into a string variable. but I am getting the whole query.
Here is my code:-
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
In strpassword i get the whole query.
But in Toad the result is as
F52377D5FFB1A47F
how to get that in oracle?

When you write
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
Then you are simply displaying the string value as you are not executing the SQL which is present inside the string.
What you are looking for is the result of the SQL which is present inside the string. To get the result of the SQL stored inside the string you need to execute it.
You can try like this:
string queryString = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader[0]));
}
}
finally
{
reader.Close();
}
}
As commented above, your query is prone to SQL Injection. A better way is to use paramterized query to get rid of it. Something like
string sql = "select sys.get_enc_val (#myvar) from dual";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("myvar", txtpassword.Text);

Related

How to display numeric value selected from MS Access in the MessageBox()?

Why does my code show the message
Data type mismatch in criteria expression.
My code:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string cq = "select sum(Fine) from studentbook where S_ID=" + textSID.Text + "";
command.CommandText = cq;
int a = Convert.ToInt32(command.ExecuteReader());
connection.Close();
MessageBox.Show(a.ToString());
Change code like this:
where S_ID = '" + textSID.Text + "'
Also use command.ExecuteScalar() instead of command.ExecuteReader():
int a = Convert.ToInt32(command.ExecuteScalar());
You should always use parameterized queries by the way. This kind of string concatenations are open for SQL Injection.

multiple queries on 1 button click

I want to perform 2 queries in one button click. I tried the
string query = "first query";
query+="second query";
But this didn't work it shows error.
I have now created 2 separate connections like below:
try
{
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
//open connection with database
conn1.Open();
//query to select all users with teh given username
SqlCommand com1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", conn1);
// comand.Parameters.AddWithValue("#id", iD);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute queries
com1.ExecuteNonQuery();
conn1.Close();
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com2 = new SqlCommand("insert into artikulli(path) values ('" + filename + "')", conn2);
//open connection with database
conn2.Open();
com2.ExecuteNonQuery();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni perzgjedhur asnje file');", true);
}
}
But the problem is that only the second query is performed and the firs is saved as null in database
In your case, there is no reason to open two connections. In addition, the C# language has evolved, so I recommend using the power given by the new language constructs (using, var).
Here is an improved version that should work assuming that the values you bind to your parameters are valid:
try
{
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString))
{
//open connection with database
connection.Open();
//query to select all users with teh given username
using(var command1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", connection))
{
command1.Parameters.AddWithValue("#tema", InputTitle.Value);
command1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
command1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
command1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute first query
command1.ExecuteNonQuery();
}
//build second query
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
using(SqlCommand command2 = new SqlCommand("insert into artikulli(path) values (#filename)", connection))
{
//add parameters
command2.Parameters.AddWithValue("#filename", filename);
//execute second query
command2.ExecuteNonQuery();
}
}
}
//TODO: add some exception handling
//simply wrapping code in a try block has no effect without a catch/finally
Try below code, No need to open the connection twice
string query1 = "insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com1= new SqlCommand(query1, conn);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
string query2 = "insert into artikulli(path) values ('" + filename + "')", conn);
comm.ExecuteNonQuery();
comm.CommandText = query2;
comm.ExecuteScalar();

Incorrect syntax near ' '

This is the page behind code where it have error
if (Session["username"] != null)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString;
string sql1 = "Select pemgrp from Profile where userID = '" + Session["username"].ToString() + "'";
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DataTable dt = new DataTable();
cmd.CommandText = sql;
cmd.Connection = con;
//open connection and execute command
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
lb_classmates.Text = dr[0].ToString();
}
}
However, when i run, it give me this error :
Incorrect syntax near the keyword 'where'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect
syntax near the keyword 'where'.
As you are using sub-query therefore this
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
and you should be using Parametereized queries to avoid SQL injection.
I think It should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
instead of
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
I would strongly recommend you to use parametereized queries
No One's answer is of course right.
If you want to use a subquery in a query, you should use IN (Transact-SQL)
Determines whether a specified value matches any value in a subquery
or a list.
test_expression [ NOT ] IN
( subquery | expression [ ,...n ]
)
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also consider to use using to dispose your SqlConnection.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString))
{
connection.Open();
string sql1 = "Select pemgrp from Profile where userID = #username";
string sql = "Select studname from Profile where pemgrp IN (" + sql1 + ")";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#username", Session["username"].ToString());
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//
}
}
You should use parameterized query something llike this
string sql = "Select studname from Profile where pemgrp = #p1";
and to pass parameter
command.Parameters.AddWithValue("#p1",sql1);

Whats wrong with my MS Access Update Query?

Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....

MySQL Password Login Code?

I'm trying to do a Login code in C# with MySQL. Basically the user enters a username and password then the code checks the database if the the password is correct. I'm having trouble getting the code to read from the data base... Here is where I'm at.
public string strUsername;
public string strPassword;
//Connect to DataBase
MySQLServer.Open();
//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
string TruePass = mySQLReader.GetString(1);
if (strPassword == TruePass)
{
blnCorrect = true;
//Get Player Data
}
}
MySQLServer.Close();
From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. I am still fairly new to MySQL so any help would be Great.
Non-numeric field value must be enclosed with single quote.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
but you have to use Parameters to prevent SQL Injection.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =#username";
mySQLCommand.Connection=MySQLServer;
mySQLCommand.Parameters.AddWithValue("#username",strUsername);
string con_string = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
SqlConnection Con = new SqlConnection(con_string);
SqlCommand Com = new SqlCommand(query, Con);
Con.Open();
SqlDataReader Reader;
Reader = Com.ExecuteReader();
if (Reader.Read())
{
lblStatus.Text="Successfully Login";
}
else
{
lblStatus.Text="UserName or Password error";
}
Con.Close();
As AVD said you should use parameters to prevent sql injection....

Categories