Is it even possible to return value of string without the " " ?
I have the following string: Chb = "NOT";
Now i either want to remove the "" in C# or SQL.
so i want to have either Chb = NOT in C#
,or i want to remove the ' ' in SQL that i get in #Chb so that this:
WHERE PAR #Chb IN ('1','2','3')
isnt like this : WHERE PAR 'NOT' IN ('1','2','3')
but it is like this WHERE PAR NOT IN ('1','2','3')
I don't believe this is the right approach for this.
If you want to execute a command in SQL which comes from a C# code, then i would do:
string exists = "select * from table where var in (1,2,3)";
string notExists = "select * from table where var NOT in (1,2,3)";
if (chb != "NOT")
{
SqlCommand cmd = new SqlCommand(exists, con);
cmd.ExecuteScalar();
}
else
{
SqlCommand cmd = new SqlCommand(notExists, con);
cmd.ExecuteScalar();
}
Related
Case: I'm trying execute a query in C# with MySql.Data.MySqlClient, which containts INSERT INTO, i'm getting an error(see below):
Database table:
What im trying to achieve: I want to insert into a new record with: "value_id(Auto Increment)", "machine_id" "tag_name", "int_value", "real_value" and "bool_value";
I have the following code:
*Retrieving machine ID
private void getMachineID()
{
string connStr = "";
string ipAdressID = "'" + machineIP + "'";
string basicQueryID = "SELECT machine_id FROM machine WHERE machine.machine_ip LIKE ";
string totalQueryID = basicQueryID + ipAdressID;
//Create connection
MySqlConnection conn = new MySqlConnection(connStr);
//Query command
MySqlCommand cmd = conn.CreateCommand();
//Assign string to query
cmd.CommandText = totalQueryID;
//Open connection
conn.Open();
//Get result ID from machine where IP adress = machineIP and write to machineID variable.
machineID = (int)(cmd.ExecuteScalar());
}
Code to insert into the record:
try
{
string connStr = "";
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO waardes(machine_id, tag_name, int_value, real_value, bool_value) VALUES(#machineID, #tagName, #intValue, #doubleValue, #boolValue)";
cmd.Parameters.AddWithValue("#tagName", tagName);
cmd.Parameters.AddWithValue("#intValue", intValue);
cmd.Parameters.AddWithValue("#doubleValue", doubleValue);
cmd.Parameters.AddWithValue("#boolValue", boolValue);
cmd.Parameters.AddWithValue("#machineID", machineID);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Hope you guys can help!
There's no INSERT with where clause.
Take a look at this question: How to insert with where clause
Maybe, you can create an IF inside your app to verify your parameters before executing the INSERT statement.
Based on your query, I believe you need an UPDATE:
UPDATE waardes SET tag_name = #tagName,
int_value = #intValue, real_value = #doubleValue,
bool_value = #boolValue WHERE machine.machine_id LIKE %1%
Is this what you need?
you cannot use where in insert statement, because insert statement is used for adding new rows to table. you better use update statement.
There can be no Where clause used with Insert. However you can use Where when you are using Insert Into. In your statement I suppose you are missing the Select From before your Where clause.
Consider the example:
INSERT INTO tableNameDestination
SELECT feild(s),...
FROM tableNameSource
WHERE Condition
In your case:
INSERT INTO waardes(tag_name, int_value, real_value, bool_value) VALUES(#tagName, #intValue, #doubleValue, #boolValue) Select field1, field2, field3, field4 from machine WHERE machine.machine_id LIKE " + "'" + machineID + "'";
I have a database with the infos of the buyers of my product, but I would like it to send the value provided by the program to the database, if it is null, how can I do this?
Code:
I have a database with the infos of the buyers of my product, but I would like it to send the value provided by the program to the database, if it is null, how can I do this?
Code:
string comando = "SELECT COUNT(*) FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
var connection = new MySqlConnection(connString);
var cmd = new MySqlCommand(comando, connection);
cmd.Parameters.AddWithValue("#Usuario", usuario);
cmd.Parameters.AddWithValue("#Senha", senha);
var command = connection.CreateCommand();
connection.Open();
MySqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
hd_id = leitor["id"].ToString();
}
if (hd_id == null)
{
//Code i need here
}
int retorno = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
There is quite a bit that has been lost in translation in this question, but from I think I am reading I think you want the ID from the database to be retrieved. But the query is just running a count command which will not contain that.
string comando = "SELECT COUNT(*) FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
should actually be
string comando = "SELECT id FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
As you are only returning 1 value (or null if no record match) then you do not need to use a reader; and you can read the return directly, and check for null
var sqlReturn = cmd.ExecuteScalar();
if (sqlReturn == null) { /* Code i need here */ }
else { hd_id = (int)sqlReturn; }
If I did not understand the question; please feel free to let me know and we'll see if we can get you fixed up.
C#
cmd.Parameters.AddWithValue("#Usuario", String.IsNullOrEmpty(usuario) ? DBNull.Value : usuario);
cmd.Parameters.AddWithValue("#Senha", String.IsNullOrEmpty(senha) ? DBNull.Value : senha);
I have a simple .aspx login website and I use OleDB for local validation.
Here is my problem: After finding SQL Injection vulnerability, I decided to use parameters. But after using parameters my response is always "0" (Same as "Authenticated=false"). But if I don't use parameters, my response is "1" (Same as "Authenticated=true").
Here some pics while debugging:
Without parameters where the response=1 (Authenticated):
With code:
string idstr = Request.QueryString["id"];
idstr.Replace("''", "");
string passpath = Request.QueryString["password"];
passpath.Replace("''", "");
OleDbConnection connect = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= C:\Users\hugow_000\Desktop\OSGS_Kantine_htm_design\Kantine_data.accdb; Persist Security Info = False;";
cmd.Connection = connect;
connect.Open();
cmd.CommandText = "select * from User_data where Stamnummer="+idstr+" and Wachtwoord="+ passpath;
OleDbDataReader read = cmd.ExecuteReader();
int code = 0;
while (read.Read())
{
code = code + 1;
}
if (code == 1)
{
Response.Redirect("~/AuthKeyGEN.aspx?Auth=true&id=" + idstr + "&password=" + passpath + "");
}
if (code > 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
if (code < 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
}
And with parameters where the response is 0 (Not Authenticated):
And with code:
string idstr = Request.QueryString["id"];
idstr.Replace("''", "");
string passpath = Request.QueryString["password"];
passpath.Replace("''", "");
OleDbConnection connect = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= C:\Users\hugow_000\Desktop\OSGS_Kantine_htm_design\Kantine_data.accdb; Persist Security Info = False;";
cmd.Connection = connect;
connect.Open();
cmd.CommandText = "select * from User_data where Stamnummer=#idstr and Wachtwoord=#passpath";
cmd.Parameters.Add("#idstr", OleDbType.BSTR).Value = idstr;
cmd.Parameters.Add("#passpath", OleDbType.BSTR).Value = passpath;
OleDbDataReader read = cmd.ExecuteReader();
int code = 0;
while (read.Read())
{
code = code + 1;
}
if (code == 1)
{
Response.Redirect("~/AuthKeyGEN.aspx?Auth=true&id=" + idstr + "&password=" + passpath + "");
}
if (code > 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
if (code < 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
}
I am using the same credentials in both scenarios,
So why is my response always 0 if I use parameters in here?
Thanks in advance!
Doesn't look anything wrong but try using OleDbType.VarChar instead of OleDbType.BSTR since both the parameter are of string type; like
cmd.Parameters.Add("#idstr", OleDbType.VarChar).Value = idstr;
cmd.Parameters.Add("#passpath", OleDbType.VarChar).Value = passpath;
Also as a side note, instead of using select * use a count() query like below in which case you can use ExecuteScalar() rather than using ExecuteReader()
"select count(*) from User_data
where Stamnummer=#idstr and Wachtwoord=#passpath";
Ms Access uses ? as parameter place holders and the order is important (your order is correct). The parameter objects can be named as the name is ignored by the engine so it really does not matter but might make for more readable code. See OleDbCommand.Parameters as reference.
cmd.CommandText = "select 1 from User_data where Stamnummer = ? and Wachtwoord= ?";
Also change the parameter types as #Rahul had pointed out to VarChar.
General recommendations
Wrap your connection in a using block.This ensures your connection is always closed even when an Exception is encountered.
Like #Rahul said use ExecuteScalar instead of ExecuteReader. Use either COUNT(*) or hardcode 1 as the result: select 1 from User_data ...
Never ever store passwords as plain text, ever! This is horrible practice and makes for a very unsecure app. I have submitted a complete solution to creating a password hash that you could copy/paste and use directly.
I'm trying to translate some perl code into C# and I'm having some trouble with the following.
After establishing a sql server connection and executing the select statement, how do I reference the different elements in the table columns. For example, in Perl it looks like:
my $dbh = DBI -> connect( NAME, USR, PWD )
or die "Failed to connect to database: " . DBI->message;
my $dbname = DB_NAME;
my $dbschema = DB_SCHEMA;
my $sql = qq{select a,b,c,d,e,f,g,h,i,...
from $dbname.$dbschema.package p
join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
join $dbname.$dbschema.download d on pd.download_id = d.download_id
where p.package_name = '$package'
--and ds.server_address like 'tcp/ip'
order by a,b,c,d,..};
my $sth = $dbh -> prepare( $sql )
or die "Failed to prepare statement: " . $dbh->message;
$sth -> execute()
or die "Failed to execute statement: " . $sth->message;
#now to go through each row in result table
while ( #data = $sth->fetchrow_array() )
{
print "$data[0]";
# If source server FTP is not already open, make new FTP
if ( $data[0] != $src_id )
{
if ( $src_ftp )
{ $src_ftp -> quit; }
$src_ftp = make_ftp( $data[1], $data[2], $data[3], $data[18], $data[19], $data[20] );
$src_id = $data[0];
}
}
so far I've got it down to
string db = NAME;
string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD
SqlConnection myConnection = new SqlConnection(myConnectionString);
string myInsertQuery = "select a,b,c,d,e,f,g,h,i,...
from $dbname.$dbschema.package p
join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
join $dbname.$dbschema.download d on pd.download_id = d.download_id
where p.package_name = '$package'
--and ds.server_address like 'tcp/ip'
order by a,b,c,d,..";
SqlCommand myCommand = new SqlCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
but how do I reference the columns like data[0] and data[1] in C#. Sorry I'm new to both languages so my background is severely lacking. Thanks!
You could reference your column directly by its column name or by numeric order (it starts with 0 as the first column) either through a DataTable, DataSet, DataReader or a specific DataRow.
For the sake of example i'll use a DataTable here and I will name it as dt and let's say we want to reference the first row then you could reference it with the following Syntax/Format:
dt[RowNumber]["ColumnName or Column Number"].ToString();
For example:
dt[0]["a"].ToString();
Or by number the first column with be 0 like:
dt[0][0].ToString();
And use Parameters by the way because without which it would be susceptible to SQL Injection. Here's a more complete code below:
string db = NAME;
string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
string mySelectQuery = #"SELECT a,b,c,d,e,f,g,h,i,...
FROM package p
JOIN package_download pd on p.package_id = pd.package_id
join download d on pd.download_id = d.download_id
WHERE p.package_name = #PackageName
AND ds.server_address LIKE 'tcp/ip%'
ORDER by a,b,c,d";
try
{
connection.Open();
using (SqlDataAdapter da = new SqlDataAdapter(mySelectQuery, connection))
{
using (SqlCommand cmd = new SqlCommand())
{
da.SelectCommand.Parameters.AddWithValue("#PackageName", txtPackage.Text);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count>0) // Make sure there is something in your DataTable
{
String aVal = dt[0]["a"].ToString();
String bVal = dt[0]["b"].ToString();
// You'll be the one to fill up
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I change your LIKE 'tcp/ip' to LIKE 'tcp/ip%' by the way which is the more appropriate one of using LIKE.
you can use ado.net entity data table to reference the tables in your sql server. I don't know if you're asking exactly this but it may help. because direct referencing to sql server is not possible as far as i know.
here i have tried to select a data from db make use of like statement, but it has search with the 1st digit of my data. but i need to write the code, like search instead of first 3 digit of my data. can any one help me.
public void CC()
{
CCddl.Items.Clear();
ListItem l = new ListItem();
l.Text = "-Select-";
CCddl.Items.Add(l);
CCddl.SelectedIndex = 0;
con.Open();
SqlCommand cmd = new SqlCommand("select Componetcode from dbo.tbl_component where Sitecode like '%" + TextBox1.Text + "%'", con);
SqlDataReader dr1;
dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
ListItem n = new ListItem();
n.Text = dr1["Componetcode"].ToString().Trim();
CCddl.Items.Add(n);
}
dr1.Close();
con.Close();
}
you cannot operate the like on number you need to convert number to stirng by using cast or convert ...
EDIT
you can also make use of substring function to skip frist three char or your data in column
select * from (
select column1,cast(column2 as varchar(30)) as column2 from tablename
) d where
substring(column2,4, LEN(column2) - 3 ) like '%textosearch%'
you need to write down
select * from tablename where column like '___textosearch%'
so your code will be
SqlCommand cmd = new SqlCommand("select Componetcode from dbo.tbl_component
where Sitecode like '___" + TextBox1.Text + "%'", con);
_ allows you to match on a single character in sql , so you need to write three "_" as i done in my code
Also modify you code with sql parameter so taht it avoid SQL injection attack